Vue3 從零到一,setup() 新嘗試

Vue3 RC,發(fā)布咯,可以嘗鮮了

關(guān)鍵字 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>",
            "http:// @ 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() {
    //顯示當(dāng)前路徑
    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

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

友情鏈接更多精彩內(nèi)容