关于前端:Vue3和Vue2的不同及替代方案

setup中不能用this

this.$message 须要用 import { ElMessage } from ‘element-plus’

ElMessage.success({
  message: '保留胜利'
})

//Vue2旧用法
this.$message({
    type: success,
    message: '保留胜利'
})

refs的值要用value获取

<el-form
    ref="newCreatForm"
    :model="newCreat"
>

办法中援用时 要用newCreatForm.value能力获取实例, newCreatForm由装璜器setup返回 const newCreatForm = ref()

setup中如何应用vuex

应用useStore

import { useStore } from "vuex";

export default {
  name: "About",
  components: {},
  setup() {
    const store = useStore()
    function plus() {
      //store.state.count++
      store.commit('increment')
    }
    return { plus }
  }
setup中应用 computed
import { computed } from "vue";
export default {
  name: "About",
  components: {},
  setup() {
    const store = useStore()
    function plus() {
      store.commit('increment')
    }
    // 新用法
    const count = computed(() => {
      return store.state.count
    })
    return { plus, count }
  },
  // Vue2传统用法
  computed: {
    // count () {
      // return this.$store.state.count
    // }
  },
  methods: {
    // plus() {
    //   this.$store.state.count++;
    // }
  },
};

setup中mapMutation如何应用模块中的mutation办法?

const change = mapMutations('user',{change: "changeName"}) // user命名空间 change别名, changeName 命名空间中的实在函数名称
return { ...change };

Vue2中传统用法

methods: {
...mapMutations({
        change: 'user/changeName'
    })
}

setup中应用mapActions

const plus = mapActions({plus: 'increment'});
return { ..plus };
// 返回的就是页面所须要的函数, 能够间接用 如果不同名 必须用对象赋值别名! 即页面中用的是plus, 而store中是increment的状况. 如果同名能够用数组['plus']

测试在vue3中mapState跟mapGetters在setup函数返回的对象构造进去的state跟getters是函数,这个函数应该放在computed函数中,其返回值才是咱们真正想获取到的响应式的值。特地留神的是这个函数咱们在当作参数传递给computed时,咱们要显示的为这个函数绑定this为 {$store:store} ;mapMutations跟mapActions在setup间接返回能够在template失常应用

评论

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注

这个站点使用 Akismet 来减少垃圾评论。了解你的评论数据如何被处理