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>

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值