上一篇已经对Vue2和Vue3的组件开发区别讲了一部分,如需了解请移步:
带你体验Vue2和Vue3开发组件的区别(一),
主要讲了template、data、methods、Lifecyle Hooks这几个的区别,接下来我们再讲讲另外几个属性的变化。
1.Computed Properties
Computed Properties-计算属性,这里就不多讲,只做个对比,如果需要了解详细的计算属性可以参照Vue中的computed和watch的区别,里面解释了计算属性的详细用法及和watch的区别。
Vue2
export default { // .. computed: { formatData() { // 方法 } }}
Vue3
Vue3 使用计算属性,需要先在组件内引入computed。
import { reactive, computed } from 'vue'export default { setup () { const data = reactive({ userName: '', lowerCaseUsername: computed(() => data.userName) }) // .. }}
2.Emitting Events
自定义事件大多数用在组件间通讯上。
Vue2
在Vue2中我们直接用this.$emit触发,,前面是方法名称,后面是参数。
this.$emit('login', {})
Vue3
Vue3中,this的指向已经变了,所以在setup中不能使用this,
setup (props, { emit }) { // ... const login = () => { emit('login', {}) } // ...}
setup()方法可以接收两个参数:
props - 不可变的组件参数
- context - Vue3 暴露出来的属性(emit,slots,attrs)
3.Props
接收父组件props参数传递这一块区别也蛮大,主要是this不能使用了。
Vue2
this代表的是当前组件,所以可以直接获取属性值
<template> <div class="about"> <button @click="clickBtn">点击</button> </div></template><script>export default { props: { title: String }, data() { return { }; }, methods: { clickBtn() { console.log(this.title); } }};</script>
Vue3
this无法直接拿到props属性,但是setup提供了参数,我们可以获取。
<template> <button @click="clickBtn">点击</button></template><script>import { reactive } from "vue";export default { props: { title: String }, setup(props) { const data = reactive({}); const clickBtn = () => { console.log(props.title); }; return { clickBtn, data }; }};</script>
4.watch
看到上面的,应该能想到使用区别了。
Vue2
如想要了解Vue2 watch的详细信息请:
Vue中的computed和watch的区别
<template> <div> <input type="text" v-model="a" /> <div>a={{ a }}</div> <div>c={{ c }}</div> </div></template><script>export default { data() { return { a: "", c: "" }; }, watch: { a(val) { console.log(val); this.c = val + "数据"; } }};</script>
Vue3
首先从vue中引入,接下来
<template> <input type="text" v-model="data.username" placeholder="Username" /></template><script>import { reactive, watch } from "vue";export default { setup() { const data = reactive({ username: "" }); // 监听 watch( () => data.username, (oldVlaue, newValue) => { console.log(oldVlaue, newValue, "改变"); } ); return { data }; }};</script>
第一个参数是一个响应式对象
第二个是对象发生变化时执行的函数体
回调函数包含两个参数,分别为 newValue ,oldValue
可以监听多个对象,第一项改为数组即可
如果监听reactive对象时,需要使用函数返回值的方法