Vue学习笔记 单向数据流机制

单向数据流

数据从父级组件传递给子组件,只能单向绑定。子组件内部不能直接修改从父组件传递过来的数据。

如果要使用父组件传递过来的变量值,需要在组件内的数据项中声明一个变量,把父组件传递过来的变量赋值给内部变量,然后就可以随意修改了。

 

Demo21.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Hello World</title>
    <script src="https://unpkg.com/vue@next"></script>
</head>
<body>
    <div>
        <h4>单向数据流</h4>
        <p>数据从父级组件传递给子组件,只能单向绑定。子组件内部不能直接修改从父组件传递过来的数据。</p>
        <p>如果要使用父组件传递过来的变量值,需要在组件内的数据项中声明一个变量,把父组件传递过来的变量赋值给内部变量,然后就可以随意修改了。</p>
        <br>
    </div>
    <div id="app"></div>
</body>
<script>
    const app = Vue.createApp({
        data() {
            return {
                counter: 123
            }
        },
        template: `
        <div>单向数据流</div>
        <global :counter="counter"/>
        <br>
        
        `
    });
    app.component('global', {
        props: ['counter'],
        data() {
            return {
                newCounter: this.counter
            }
        },
        template: `
            <h3>直接操作父组件变量 {{counter}}</h3>
            <button @click="this.counter+=1">直接操作父组件变量</button>
            
            <h3>操作组件内部变量 {{newCounter}}</h3>
            <button @click="this.newCounter+=1">操作组件内部变量</button>
        `
    });
    const vm = app.mount("#app");
</script>
</html>