下面总结一下我们在使用vue过程中,经常会踩到坑却会被忽略的问题:
// ... methods: { change () { this.$set(obj, ‘property‘, value) // 通过以上方式可以给obj对象的property属性设置value值,并且会重新发生响应式绑定 } } // ...
// ... data: { obj1: { pro1: ‘‘ } } // ...
<div>
<input v-model="msg" @input="inputHandle" />
</div>
// js
data: {
msg: ‘‘
},
methods: {
inputHandle () {
// 事件触发
// 触发比较早
}
},
watch: {
msg (newVal, oldVal) {
// watch 触发
// 触发比较晚
}
}
data: { msg: ‘‘ }, computed: { cmsg () { return this.msg + ‘ computed‘ } }
data: { msg: ‘‘ }, computed: { cmsg: { get () { return this.msg + ‘ computed‘ } } }
data: { msg: ‘‘ }, computed: { cmsg: { get () { return this.msg + ‘ computed‘ }, set (newVal) { // ... // 此处我们可以编写自己的业务代码 } } }, methods: { changeCmsg () { this.cmsg = ‘hello‘ // 此处会对 cmgs这个计算属性进行赋值,这时候会触发set函数。 } }
<template>
<input v-bind:value="msg" v-on:input="inputHandle($event)" />
</template>
<script>
new Vue({
data: {
msg: ‘‘,
realMsg: ‘‘
},
methods: {
inputHandle (e) {
// 给展示的数据增加 过滤效果
this.msg = filter(e.target.value)
// 给真实数据取消过滤效果
this.realMsg = deFilter(e.target.value)
}
}
})
</script>
// 注册组件 Vue.component(‘my-com‘, { template: ` <div> <input type="text" v-model="model" /> </div> `, data () { return { model: ‘‘ } }, props: [‘value‘], watch: { value (newVal, oldVal) { this.model = newVal }, model (newVal, oldVal) { this.$emit(‘input‘, newVal) } } }) // template <my-com v-model="childMsg"></my-com>
created () { this.$watch(() => this.model[this.data.prop], (newVal, oldVal) => { // ... }) }
data () { return { // ... your data } }
原文:https://www.cnblogs.com/kingsm/p/9839506.html