首页 > 其他分享 >组合api-响应式变量

组合api-响应式变量

时间:2023-02-04 18:44:48浏览次数:32  
标签:vue 变量 title 响应 api world ref hello

选项api

选项api就是把一个个属性如data,method等,作为选项把内容传给组件的对象里

App.vue

<template>
  <h1>{{ title }}</h1>
  <button @click="changeTitle">变换</button>
</template>

<script>

export default {
  data(){
    return{
      title:"hello world"
    }
  },
  methods:{
    changeTitle(){
      this.title = "hello vue"
    }
  }
}
</script>

组合api

把所有的功能写到setup方法里

<template>
  <h1>{{ title }}</h1>
  <button @click="say">按钮</button>
</template>

<script>

export default {
  //composition api 组合api
  setup(){
    let title = "hello world";
    function say(){
      alert("hello vue");
    }

    return{//用来暴露属性或方法等
      title,
      say
    }
  }
}
</script>


如果把title变了

function say(){
      title = "hello vue"
    }

按下按钮显示的hello world也还是不变,这就涉及到响应式的概念
如果title是响应式的,那title值变了,按下按钮后会跟着变,但现在的title只是普通的变量
要将title变为响应式的变量就要引入vue中的ref方法

import {ref} from "vue";

然后把hello world字符串用ref括起来变成响应式变量

let title = ref("hello world");

改变响应式变量的值用它的value属性
title.value = "hello vue"

<template>
  <h1>{{ title }}</h1>
  <button @click="say">按钮</button>
</template>

<script>

import {ref} from "vue";
export default {
  //composition api 组合api
  setup(){
    let title = ref("hello world");
    function say(){
      title.value = "hello vue"
    }

    return{//用来暴露属性或方法等
      title,
      say
    }
  }
}
</script>

reactive方法可以将对象变成响应式的

<template>
  <h1>{{ student.name }}</h1>
  <button @click="change">按钮</button>
</template>

<script>

import {reactive} from "vue";
export default {
  //composition api 组合api
  setup(){

    const student = reactive({name:"benson",age:18})
    function change(){
      student.name = "mike"
    }

    return{//用来暴露属性或方法等
      student,
      change
    }
  }
}
</script>


标签:vue,变量,title,响应,api,world,ref,hello
From: https://www.cnblogs.com/ben10044/p/17092124.html

相关文章