Vue3+.net6.0 三 响应式基础,methods

发布时间 2023-07-11 10:41:34作者: luytest

这里的示例都用选项式风格

在 Vue 3 中,数据是基于 JavaScript Proxy(代理) 实现响应式的。

这个示例中输出是false,因为当你在赋值后再访问 this.someObj,此值已经是原来的 newObj 的一个响应式代理。

需要注意的是newObj 并不会变成响应式。

<script type="module">
    const { createApp } = Vue;
    const app = createApp({
        data() {
            return {
                someObj:{}
            }
        },
        mounted(){
            const newObj = {};
            this.someObj = newObj;
            console.log(this.someObj === newObj);
        }
    });
    app.mount('#appDiv');
</script>

 

方法methods

和Vue2一样,声明方法都是用methods。

定义一个属性count,在方法中让 count++。

const app = createApp({
        data() {
            return {
                //someObj:{}
                count:0,
            }
        },
        methods:{
            addCount(){
                this.count++;
            }
        }
    });

页面上来个按钮

 <button @@:click="addCount">点我++</button>  {{count}}

效果跟之前的例子是一样的,点击按钮触发addCount,令count++。

 

更新时机

当你更改响应式状态后,DOM 会自动更新。然而,你得注意 DOM 的更新并不是同步的。相反,Vue 将缓冲它们直到更新周期的 “下个时机” 以确保无论你进行了多少次状态更改,每个组件都只更新一次。

 

深层响应性

这个对比Vue2,在使用方面主要是影响到对象和数组类型的操作。

1.对象类型:

  在Vue2中,为对象新增属性后,虽然成功,但是不会被监听,但是Vue3中可以。

html部分:

<p v-for="(val,key,index) in person">
        {{key}}:{{val}}
    </p>
    <button @@click="editPerson">修改person.Name</button>
    <button @@click="addPersonAttr">增加person.Age</button>

data部分:

                person:{
                    id:1,
                    name:'张三'
                },

methods部分:

            editPerson(){
                if(this.person.name=='张三')
                    this.person.name='李四';
                else 
                    this.person.name='张三';
            },
            addPersonAttr(){
                this.person.age= 30;
            }

可以看到,无论是修改对象属性值还是新增属性,都可以按我们所预想的显示出来,而在Vue2中,我们还得用Vue.set方法。

2.数组类型:

html部分:

    <p v-for="(val,index) in intArray">
        {{index}}:{{val}}
    </p>
    <button @@click="editArray">修改数组</button>&nbsp;
    <button @@click="addArray">增加数组项</button>&nbsp;
    <button @@click="spliceArray">删除数组项</button>

data部分:

 intArray:[1,3,5,7,9]

methods部分:

            editArray(){
                this.intArray[1]=0;
            },
            addArray(){
                this.intArray.push(11);
            },
            spliceArray(){
                this.intArray.splice(0,1);
            }

修改,新增元素,删除元素都能响应。