Home  >  Article  >  Web Front-end  >  Is vue data flow one-way?

Is vue data flow one-way?

青灯夜游
青灯夜游Original
2022-12-22 20:27:033314browse

is one-way. Although Vue has a two-way binding "v-model", the data transfer between Vue parent and child components still follows a one-way data flow. The parent component can pass props to the child component, but the child component cannot modify the props passed by the parent component. , child components can only notify parent components of data changes through events.

Is vue data flow one-way?

The operating environment of this tutorial: windows7 system, vue3 version, DELL G3 computer.

Vue is a one-way data flow. The data flow direction is from top to bottom, from parent components to child components.

Don’t be confused with Vue’s two-way data binding; two-way data binding refers to the rendering relationship between the view and the template, not the flow relationship of the data!

Data transfer between Vue parent and child components follows a one-way data flow. The parent component can pass props to the child component, but the child component cannot modify the props passed by the parent component. The child component can only notify the parent component of data changes through events.

1, one-way data flow:

All props form a one-way downward binding between their parent and child props: the update of the parent prop will Flows down into child components, but not the other way around. This will prevent the child component from accidentally changing the state of the parent component, making the data flow of your application difficult to understand.

In addition, every time the parent component changes, all props in the child component will be refreshed to the latest values. This means you should not change props inside a child component. If you do this, it will also change the state of the parent component.

2, Prop is passed in by reference:

Note that in JavaScript, objects and arrays are passed in by reference, so for an array or object type For props, changing the object or array itself in the child component will affect the state of the parent component.

In-depth understanding of Vue's one-way data flow

1. v-model is used on input elements

v-model It is very similar to two-way binding when used (actually...), but Vue is a single data flow, and v-model is just syntactic sugar:

<input v-model="something" />
<input v-bind:value="something" v-on:input="something = $event.target.value" />

The first line of code is actually only the second Syntactic sugar for rows. Then the second line of code can be abbreviated like this:

<input :value="something" @input="something = $event.target.value" />

To understand this line of code, first you need to know that the input element itself has an oninput event. This is a new addition to HTML5, similar to onchange. Whenever the input box When the content changes, oninput will be triggered, and the latest value will be passed to something through $event.

We carefully observe the two lines of code of syntactic sugar and original syntax, and we can draw a conclusion: When adding the v-model attribute to the input element, the value will be used as the attribute of the element by default, and then The 'input' event is used as a trigger event for real-time value transfer

2. v-model is used on components

v-model can not only be used on input It can also be used on components. Take a look at the demo on the official website.

<currency-input v-model="price"></currency-input>
Vue.component(&#39;currency-input&#39;, {
  template: &#39;\
    <span>\
      $\
      <input\
        ref="input"\
        v-bind:value="value"\
        v-on:input="updateValue($event.target.value)"\
      >\
    </span>\
  &#39;,
  props: [&#39;value&#39;], // 为什么这里要用 value 属性,value在哪里定义的?
  methods: {
    // 不是直接更新值,而是使用此方法来对输入值进行格式化和位数限制
    updateValue: function (value) {
      var formattedValue = value
        // 删除两侧的空格符
        .trim()
        // 保留 2 位小数
        .slice(
          0,
          value.indexOf(&#39;.&#39;) === -1
            ? value.length
            : value.indexOf(&#39;.&#39;) + 3
        )
      // 如果值尚不合规,则手动覆盖为合规的值
      if (formattedValue !== value) {
        this.$refs.input.value = formattedValue
      }
      // 通过 input 事件带出数值
      // <!--为什么这里把 &#39;input&#39; 作为触发事件的事件名?`input` 在哪定义的?-->
      this.$emit(&#39;input&#39;, Number(formattedValue))
    }
  }
})

If you know the answers to these two questions, then congratulations on truly mastering v-model. If you don’t understand, then you can take a look at this code:

<currency-input v-model="price"></currency-input>
所以在组件中使用时,它相当于下面的简写:
//上行代码是下行的语法糖
<currency-input :value="price" @input="price = arguments[0]"></currency-input>

So, give When adding the v-model attribute to a component, the value will be used as the attribute of the component by default, and the 'input' value will be used as the event name when binding events to the component. This is especially useful when writing components.

3. Disadvantages and solutions of v-model

When creating common components like check boxes or radio buttons, v-model is not easy to use. .

<input type="checkbox" v-model="something" />

v-model provides us with the value attribute and oninput event. However, what we need is not the value attribute, but the checked attribute, and the oninput event will not be triggered when you click this radio button. , it will only trigger the onchange event.

Because v-model is only used on input elements, this situation is easy to solve:

<input type="checkbox" :checked="value" @change="change(value, $event)"

When v-model is used on components:

<checkbox v-model="value"></checkbox>

Vue.component(&#39;checkbox&#39;, {
  tempalte: &#39;<input type="checkbox" @change="change" :checked="currentValue"/>&#39;
  props: [&#39;value&#39;],
  data: function () {
        return {
            //这里为什么要定义一个局部变量,并用 prop 的值初始化它。
            currentValue: this.value
        };
    },
  methods: {
    change: function ($event) {
      this.currentValue = $event.target.checked;
      this.$emit(&#39;input&#39;, this.currentValue);  
    }
})

In Vue version 2.2, you can customize prop/event through the model option when defining a component.

4. Vue component data flow

From the analysis of v-model above, we can understand that two-way data binding is based on one-way binding. The change(input) event is added to input elements (input, textare, etc.) to dynamically modify the model and view, that is, by triggering ($emit) the event of the parent component to modify the mv to achieve the effect of mvvm. The data transfer between Vue components is one-way, that is, the data is always passed from the parent component to the child component. The child component can have its own data maintained internally, but it does not have the right to modify the data passed to it by the parent component. When developing When the user tries to do this, vue will report an error. This is done for better decoupling between components. During development, there may be multiple sub-components that depend on certain data of the parent component. If the sub-component can modify the data of the parent component, a change in the sub-component will trigger all the data that depends on this data. The child component changes, so Vue does not recommend child components to modify the data of the parent component. Directly modifying props will throw a warning. The flow chart is as follows:

Is vue data flow one-way?

So, when you want to modify props in a child component, use the child component as a parent component, so there is

  • 1 , define a local variable and initialize it with the value of prop.
  • 2. Define a calculated property, process the prop value and return it.

[Related recommendations: vuejs video tutorial, web front-end development]

The above is the detailed content of Is vue data flow one-way?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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