What is a response
When an object responds to changes in the outside world, it is called responsive. For example, “When I punch you, you scream pain.”
Vue data response
When you make changes to the data, the view changes accordingly.
For example
1const vm = new Vue({
2 el:'#app'.3 data:{
4 name: 'Luna'
5 }
6})
Copy the code
According to the above code, the corresponding location on the page will display Luna, if vm. Name =’Pola’, will change from Luna to Pola.
But that’s normal. There are some weird ones
- Vue gives a warning when data is an empty object, for example.
1 new Vue({
2 data: {},
3 template: ` 4
{{n}}
5 `
6 }).$mount("#app");
Copy the code
- Show b on the page when data is a, because Vue only checks the first layer, eliminating the warning but not converting it to responsive
1new Vue({
2 data: {
3 obj: {
4 a: 0 // obj.a will be monitored by Vue & proxy
5 }
6 },
7 template: ` 8
9 {{obj.b}} 10
11
12 `.13 methods: {
14 setB() {
15 this.obj.b = 1;
16 }
17 }
18}).$mount("#app");
Copy the code
When you click set b, the view does not display 1 because Vue cannot listen for obj.b that does not exist at first
1. Declare the key in advance, even if it is null.
1new Vue({
2 data: {
3 obj: {
4 a: 0 // obj.a will be monitored by Vue & proxy
5 b: undefined
6 }
7 },
8 template: ` 9
10 {{obj.b}} 11
12
13 `.14 methods: {
15 setB() {
16 this.obj.b = 1;
17 }
18 }
19}).$mount("#app");
Copy the code
This is set b and it’s going to bring up a 1
2, use vue. set or this.$set
1new Vue({
2 data: {
3 obj: {
4 a: 0 // obj.a will be monitored by Vue & proxy
5 b: undefined
6 }
7 },
8 template: ` 9
10 {{obj.b}} 11
12
13 `.14 methods: {
15 setB() {
16 Vue.set(this.obj,'b'.1); $set(this.obj,'b',1)
17 }
18 }
19}).$mount("#app");
Copy the code
But!
What happens when you have an array in your data? If the array size keeps growing, there’s no way to declare all the keys in advance. It’s also troublesome to use vue. set or this.
You can use push directly from the mutation method
1new Vue({
2 data: {
3 array: ["a", "b", "c"]
4 },
5 template: `
6 <div>
7 {{array}}
8 <button @click="setD">set d</button>
9 </div>
10 `,
11 methods: {
12 setD() {
13 this.array.push("d");
14 }
15 }
16}).$mount("#app");
Copy the code
You yuxi tampered with 7 apis of the array. After calling, the UI will be updated. Please refer to the [mutation method] section of the documentation [cn.vuejs.org/v2/guide/li…