天天看點

Vue.js--元件使用props傳遞資料

基本用法

通常父元件的模闆中包含子元件,父元件要正向地向子元件傳遞資料或參數,子元件接收到後根據參數的不同來渲染不同的内容或執行操作。這個正向傳遞資料的過程就是通過props來實作的。

在元件中,使用選項props來聲明需要從父級接收的資料,props的值可以是兩種,一種是字元串數組,一種是對象。

示例:構造一個數組,接收一個來自父元件的message,并把它再元件模闆中渲染

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <script src="https://unpkg.com/vue/dist/vue.js"></script>
    <title>props</title>
</head>
<body>
    <div id="myApp">
        <my-component message="來自父元件的資料"></my-component>
    </div>
    <script>
        Vue.component('my-component',{
            props: ['message'],
            template: '<div>{{message}}</div>'
        });

        var myApp = new Vue({
            el: '#myApp'
        });
    </script>
</body>
</html>
           

props中聲明的資料與元件函數return的資料主要差別是:**props的資料來自父級,而data中的資料是元件自己的資料,作用域是元件本身。**這兩種資料都可以在模闆template及計算屬性computed和方法methods中使用。

上例的資料message就是通過props從父級傳遞過來的,在元件的字的那個一标簽上直接寫該props的名稱,如果要傳遞多個資料,在props數組中添加項即可。

注意:由于HTML特性不區分大小寫,當使用DOM模闆時,駝峰命名的props名稱要轉為短橫分割命名,例如:

<div id="app">
        <my-component warning-text="提示資訊"></my-component>
</div>
<script>
//如果使用字元串模闆,可以忽略這些限制
    Vue.component('my-component',{
        props: ['warningText'],
        template: '<div>{{warningText}}</div>'
    });

    var app = new Vue({
        el: '#app'
    });
</script>
           

有時候,傳遞的資料并不是直接寫死的,而是來自父級的動态資料,這時候可以使用指令v-bing來動态綁定props的值,當父元件的資料變化時,也會傳遞給子元件。

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <script src="https://unpkg.com/vue/dist/vue.js"></script>
    <title>動态綁定</title>
</head>
<body>
    <div id="app">
        <input type="text" v-model="parentMessage">
        <my-component :message="parentMessage"></my-component>
    </div>
    <script>
        Vue.component('my-component',{
            props: ['message'],
            template: '<div>{{message}}</div>'
        });

        var app = new Vue({
            el: '#app',
            data: {
                parentMessage: ''
            }
        });
    </script>
</body>
</html>
           
Vue.js--元件使用props傳遞資料

上例使用v-model綁定了父級的資料parentMessage,當通過輸入框任意輸入時,子元件接受到的props "message"也會實時響應,并更新元件模闆。

繼續閱讀