vue3.0初体验

安装

npm install -g @vue/cli
vue create vue-next-test
//安装vue3.0插件升级
vue add vue-next

使用

完整测试代码


import { ref, reactive, watch, computed, getCurrentInstance } from 'vue'
export default {
  name: 'Home',
  components: {
    // HelloWorld
  },
  setup() {
    // data
    const count = ref(190)
    const state = reactive({
      a: 1,
      b: {
        b2: 200
      }
    })
    const wcount = ref(0)
    const count2 = reactive({
      a: 200
    })
    // methods
    const countAdd = () => {
      count.value++
      countAdd2()
    }
    const countAdd2 = () => {
      count2.a = {
        a: 1,
        b: 2
      }
    }
    const setObj = () => {
      // state ={
      //   a: 30,
      //   b: 'sdf'
      // }
      state.a = '2sdf'
      state.b = {
        a2: '....asdf'
      }
    }
    // watch
    watch(() => count.value, val => {
      console.log(`count is ${val}`)
      wcount.value = count.value * 3
    })
    watch(() => count2.value, val => {
      console.log(`count2 is ${val}`)
    })
    // computed
    const doubleCount = computed(() => count.value * 2)

    // $route
    const { ctx } = getCurrentInstance()
    console.log(ctx.$router.currentRoute.value);

    // vuex
    const storeNum = computed(() => ctx.$store.state.storeNum)
    // update Vuex
    const updateVuex = () => {
      ctx.$store.commit('setStoreNum', 23)
    }
    return {
      state,
      setObj,
      count,
      count2,
      wcount,
      countAdd,
      countAdd2,
      doubleCount,
      storeNum,
      updateVuex
    }
  }
}

总结

data、methods、watch、computed 都写在setup中
data:简单数据类型 赋值: ref() 对象数组:reactive({})
methods: 变量引用、函数调用不需要 this.
watch: 两个参数 均为函数
computed:返回执行结果
vuex:基本没变
this: 函数中不需要,route 通过getCurrentInstance()获取ctx调用

你可能感兴趣的:(vue3.0初体验)