Vue3 从零到一,setup() 新尝试

Vue3 RC,发布咯,可以尝鲜了

关键字 ref,reactive,watch,computed,router,store

  1. 安装 vue, 新建3.0项目
npm i @vue/cli -g
vue create vue-next
cd vue-next

vue add vue-next
  1. 新建 snippet (preferences -> user snippts -> vue.json)
{
    "Vue3": {
        "prefix": "vue3",
        "body": [
            "<template>",
            "<div class='$1'>",
            "</div>",
            "</template>",
            "",
            "<script>",
            "// @ is an alias to /src",
            "",
            "export default {",
            "name:'$2',",
            "setup () {",
            "return {",
            "$3",
            "}",
            "}",
            "}",
            "</script>",
        ],
        "description": "vue3 snippt"
    }
}
  1. 修改Home.vue
<template>
  <div class="home">
    <h1>Vue3 TEST</h1>
    <p>{{num}}</p>
    <button @click="addRef">click ref ++</button>
    <p>{{count.value}}</p>
    <p>{{plus10}}</p>
    <button @click="addReactive">Click reactive ++</button>
    <p>{{status}}</p>
    <button @click="setStatus">SetStatus</button>
  </div>
</template>
<script>
// @ is an alias to /src
import { getCurrentInstance, ref, reactive, computed, watch } from "vue";

export default {
  name: "Home",
  setup() {
    //显示当前路径
    const { ctx } = getCurrentInstance();
    console.log(ctx.$router.currentRoute.value.path);

    //点击按钮 ref ++
    const num = ref(1);
    const addRef = () => {
      num.value++;
    };

    //点击按钮 reactive ++
    const count = reactive({ value: 1 });
    const addReactive = () => {
      count.value++;
    };
    watch(count, (newVal, oldVal, clean) => {
      console.log(newVal.value + "," + oldVal.value);
      clean(() => console.log("Clean"));
    });
    //计算×10
    const plus10 = computed(() => count.value * 10);

    //获取state.status
    const status = computed(() => ctx.$store.state.status);
    const setStatus = () => {
      ctx.$store.commit("setStatus", status.value);
      console.log(ctx.$store.state.status);
    };
    return {
      num,
      count,
      addRef,
      addReactive,
      plus10,
      status,
      setStatus
    };
  }
};
</script>
  1. 运行
npm run serve
 DONE  Compiled successfully in 289ms
  App running at:
  - Local:   http://localhost:8080/ 
  - Network: http://192.168.1.1:8080/

Let's see it in Vue3

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

友情链接更多精彩内容