Home > Web Front-end > JS Tutorial > body text

Problems and solutions encountered when using props to assign initial values ​​to data in Vue

不言
Release: 2018-11-27 14:54:24
forward
4528 people have browsed it

The content of this article is about the problems and solutions encountered when using props to assign initial values ​​to data in Vue. It has certain reference value. Friends in need can refer to it. I hope it will be useful to you. helped.

I was working on a project for operational activities some time ago. After it was launched, the product feedback page had something wrong. During the investigation, I found that the problem was caused by the initial value of data in Vue, and the initial value of data Comes from props. For the convenience of description, the problem is abstracted as follows:

1. Phenomenon

Code:

nbsp;html>


    <meta>
    <title>用props初始化data中变量</title>
    <script></script>


<div>
    <user-info></user-info>
</div>
<script>
    //全局组件
    let userInfo = Vue.component(&#39;userInfo&#39; ,{
        name: &#39;user-info&#39;,
        props: {
            userData: Object
        },
        data() {
          return {
              userName: this.userData.name
          }
        },
        template: `
            <div>
                <div>姓名:{{userName}}
                <div>性别:{{userData.gender}}
                <div>生日:{{userData.birthday}}
            
        `
    });

    //Vue实例
    new Vue({
        el: &#39;#app&#39;,
        data: {
            user: {
                name: &#39;&#39;,
                gender: &#39;&#39;,
                birthday: &#39;&#39;
            }
        },
        created(){
           this.getUserData();
        },
        methods:{
            getUserData(){
                setTimeout(()=>{
                    this.user = {
                        name: &#39;于永雨&#39;,
                        gender: &#39;男&#39;,
                        birthday: &#39;1991-7&#39;
                    }
                }, 500)
            }
        },
        components: {
            userInfo
        }
    });
</script>

Copy after login

Code interpretation:

  1. There is an object in the root component data: user, which contains three attributes: name, gender, and birthday. The initial values ​​​​are all empty strings.

  2. Simulate asynchronous API requests. After 500 milliseconds, the user is reassigned, and the three attributes are no longer empty.

  3. Declare a subcomponent userInfo, and there is an object userData in the props, which is used to receive the user of the parent component; There is a variable userName in data, the initial value comes from userData.name

Result:

Problems and solutions encountered when using props to assign initial values ​​to data in Vue

page After initialization, the name, gender, and birthday are all displayed as empty. After 500 milliseconds, the gender and birthday display normal results, and only the name does not change.

Why is this so?

My initial idea: user.name is String, which belongs to the basic data type. Use it to assign values ​​to userName in the child component data. It belongs to the basic data type assignment, so when user.name in the parent component changes , the userName in the subcomponent will not change accordingly.

Is that so? So I decided to change user.name to an object, assign the value by reference to the data type, and then observe whether it meets expectations. The code is as follows:

nbsp;html>


    <meta>
    <title>用props初始化data中变量-对象形式</title>
    <script></script>


<div>
    <user-info></user-info>
</div>
<script>
    //全局组件
    let userInfo = Vue.component(&#39;userInfo&#39; ,{
        name: &#39;user-info&#39;,
        props: {
            userData: Object
        },
        data() {
          return {
              userName: this.userData.name
          }
        },
        template: `
            <div>
                <div>姓名:{{userName.text}}
                <div>性别:{{userData.gender}}
                <div>生日:{{userData.birthday}}
            
        `
    });


    //Vue实例
    new Vue({
        el: &#39;#app&#39;,
        data: {
            user: {
                name: {text: &#39;&#39;},
                gender: &#39;&#39;,
                birthday: &#39;&#39;
            }
        },
        created(){
           this.getUserData();
        },
        methods:{
            getUserData(){
                setTimeout(()=>{
                    this.user = {
                        name: {text: &#39;于永雨&#39;},
                        gender: &#39;男&#39;,
                        birthday: &#39;1991-7&#39;
                    }
                }, 500)
            }
        },
        components: {
            userInfo
        }
    });
</script>

Copy after login

Running result: The name still has no value, the same as the first result! ! !

2. Reason

So, what is the reason? I was puzzled. Later, when discussing with my friends, someone asked: Could it be because the data is deeply copied during initialization?

I think this explanation is more reliable, so I went to collect evidence. First, I went to the Vue official website to read the documents about data, among which:

Problems and solutions encountered when using props to assign initial values ​​to data in Vue

When you see the word "recursively", you can basically conclude that the above inference is correct, because the core principle of deep copy is recursion.

It turns out that Vue will recursively traverse all properties of data during initialization, and use Object.defineProperty to convert all these properties into getters/setters for two-way binding. The official document clearly states in the Reactivity in Depth chapter:

Problems and solutions encountered when using props to assign initial values ​​to data in Vue

also explains why Vue does not support IE8: IE8 Object.defineProperty is not supported.

3. Solution

Since data cannot be updated as props change due to deep copy of data, we naturally think of two monitoring functions in Vue. Functions: watch, computed.
Modify the code as follows and observe the results:

nbsp;html>


    <meta>
    <title>解决方案:watch、computed</title>
    <script></script>


<div>
    <user-info></user-info>
</div>
<script>
    //全局组件
    let userInfo = Vue.component(&#39;userInfo&#39; ,{
        name: &#39;user-info&#39;,
        props: {
            userData: Object
        },
        data() {
          return {
            userName: this.userData.name
          }
        },
        computed: {
            computedUserName(){
                return this.userData.name
            }
        },
        watch: {
            &#39;userData.name&#39;: function (val) {//监听props中的属性
                this.userName = val;
            }
        },
        template: `
            <div>
                <div>姓名(watch):{{ userName }}
                <div>姓名(computed):{{ computedUserName }}
                <div>性别:{{ userData.gender }}
                <div>生日:{{ userData.birthday }}
            
        `
    });


    //Vue实例
    new Vue({
        el: &#39;#app&#39;,
        data: {
            user: {
                name: &#39;&#39;,
                gender: &#39;&#39;,
                birthday: &#39;&#39;
            }
        },
        created(){
           this.getUserData();
        },
        methods:{
            getUserData(){
                setTimeout(()=>{
                    this.user = {
                        name: &#39;于永雨&#39;,
                        gender: &#39;男&#39;,
                        birthday: &#39;1991-7&#39;
                    }
                }, 500)
            }
        },
        components: {
            userInfo
        }
    });
</script>

Copy after login

Running results

Problems and solutions encountered when using props to assign initial values ​​to data in Vue

##Perfect ! ! !

4. Summary: Key points about props in Vue

Afterwards, I carefully read the documentation about props:

Problems and solutions encountered when using props to assign initial values ​​to data in Vue

Let’s briefly summarize:

1. Props is a one-way data flow: data changes in the parent component are reflected in the child components in real time through props, and vice versa

2 . Direct manipulation of props in subcomponents is not allowed

3. Props can be manipulated in disguise

(1) Declare local variables in data and initialize them with props.

Disadvantages: local variables do not follow Update

as props are updated (2) After converting the props value in computed, output

The above is the detailed content of Problems and solutions encountered when using props to assign initial values ​​to data in Vue. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:segmentfault.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!