美文网首页
vue3 setup和ref

vue3 setup和ref

作者: 小李不小 | 来源:发表于2021-05-27 21:47 被阅读0次

vue3跟vue2的使用语法,完全不相同了,vue3所有方法变量多写在了setup里面了。

然后我开始改写<script>部分,使用setup()新语法,写了这个就不需要再写data这样的东西了。然后在setup中加入一个girls变量,为了能让模板中进行使用,还需要返回。(有的小伙伴此时可能会感觉有点复杂,没有 Vue2 直接写 data 那么直观,但这正式 Vue3 的先进之处,不用暴漏在界面中的变量就可以不进行返回了。精确控制那些方法和变量被导出和使用
<template>
  <div id="nav">
      <h1>大鹏洗浴中心欢迎你</h1>
      <button 
      v-for="(item,index) in girls"
      :key="index"
      @click="selectGirlFun(index)"
      >{{item}}</button>
//把这三个美女用按钮的形式展示在页面上,这里使用v-for语法。代码如下:
      <div>请选择一位美女为你服务</div>
      <div>我选择了{{selectGirl}}</div>
      <HelloWorld msg="我是组件"/>   
  </div>
</template>

<script>
import {defineComponent,ref} from 'vue'
import HelloWorld from './components/HelloWorld.vue';
export default defineComponent({
  name:'App',
  components:{HelloWorld},
  setup(){
      const girls=ref(["大脚", "刘英", "晓红"]);//定义一个变量
      const selectGirl =ref('');//定义一个空变量
      const selectGirlFun=(index:numebr)=>{//定义一个方案
//index:numebr 这是ts的语法,申明一个变量为数值
        console.log(index);
//给新变量赋值,必须加上vue
        selectGirl.value=girls.value[index];
      }
 //因为在模板中这些变量和方法都需要条用,所以需要return出去。
    return {
      girls,
      selectGirl,
      selectGirlFun,
    };
  },
});
</script>
      return{
        girls,//反回定义的数组
        selectGirl,//返回方法得到的新结果
        selectGirlFun,//必须返回方法名字才能执行该方法
      };
  }
})
</script>

<style>
button{margin-right:10px;}
</style>

看效果

相信大家已经看出来了,上面的vue3语法比vue2还麻烦,怎么解决呢,请关注我,使用reactive里面优化方案。

image.png

相关文章

网友评论

      本文标题:vue3 setup和ref

      本文链接:https://www.haomeiwen.com/subject/ivodsltx.html