Vue props 單向數據流


1、props通信

注意:DOM模板的駝峰命名props要轉為短橫分割命名。

<!DOCTYPE html>
<html lang="zh">

    <head>
        <meta charset="UTF-8" />
        <title>Vue</title>
    </head>

    <body>
        <div id="app">
            <my-component message='來自父組件的數據' warning-text="提示信息"></my-component>

        </div>
        <script src="https://cdn.bootcss.com/vue/2.5.9/vue.min.js"></script>
        <script type="text/javascript"> Vue.component('my-component', { template: '<div>{{warningText}}:{{message}}</div>', props: ['message', 'warningText'] }) new Vue({ el: "#app" }) </script>
    </body>

</html>

傳遞動態數據(v-bind):

<!DOCTYPE html>
<html lang="zh">

    <head>
        <meta charset="UTF-8" />
        <title>Vue</title>
    </head>

    <body>
        <div id="app">
            <input type="text" v-model="parentMessage" />
            <my-component :message='parentMessage'></my-component>

        </div>
        <script src="https://cdn.bootcss.com/vue/2.5.9/vue.min.js"></script>
        <script type="text/javascript"> Vue.component('my-component', { template: '<div>{{message}}</div>', props: ['message'] }) new Vue({ el: "#app", data: { parentMessage: '' } }) </script>
    </body>

</html>

2、單向數據流

(1)子組件保存父組件傳遞過來的值,在子組件自己的作用域下修改和使用。

<!DOCTYPE html>
<html lang="zh">

    <head>
        <meta charset="UTF-8" />
        <title>Vue</title>
    </head>

    <body>
        <div id="app">

            <my-component :init-count='1'></my-component>

        </div>
        <script src="https://cdn.bootcss.com/vue/2.5.9/vue.min.js"></script>
        <script type="text/javascript"> Vue.component('my-component', { template: '<div>{{initCount}}</div>', props: ['initCount'], data: function() { return this.initCount } }) new Vue({ el: "#app" }) </script>
    </body>

</html>

(2)使用計算屬性

<!DOCTYPE html>
<html lang="zh">

    <head>
        <meta charset="UTF-8" />
        <title>Vue</title>
    </head>

    <body>
        <div id="app">

            <my-component :width='100'></my-component>

        </div>
        <script src="https://cdn.bootcss.com/vue/2.5.9/vue.min.js"></script>
        <script type="text/javascript"> Vue.component('my-component', { template: '<div :style="style">組件內容</div>', props: ['width'], computed: { style: function() { return { width: this.width + 'px' } } } }) new Vue({ el: "#app" }) </script>
    </body>

</html>

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM