在Vue.js 2中将道具作为初始数据传递的正确方法是什么?

JavaScript

神乐古一

2020-03-10

因此,我想将道具传递给Vue组件,但是我希望这些道具将来从该组件内部进行更改,例如,当我使用AJAX从内部更新该Vue组件时。因此它们仅用于组件的初始化。

我的cars-listVue组件元素,我将具有初始属性的道具传递给single-car

// cars-list.vue

<script>
    export default {
        data: function() {
            return {
                cars: [
                    {
                        color: 'red',
                        maxSpeed: 200,
                    },
                    {
                        color: 'blue',
                        maxSpeed: 195,
                    },
                ]
            }
        },
    }
</script>

<template>
    <div>
        <template v-for="car in cars">
            <single-car :initial-properties="car"></single-car>
        </template>
    </div>
</template>

我现在的操作方式是在single-car组件内部将其分配 this.initialPropertiesthis.data.propertieson created()初始化钩子。它的工作原理是反应性的。

// single-car.vue

<script>
    export default {
        data: function() {
            return {
                properties: {},
            }
        },
        created: function(){
            this.data.properties = this.initialProperties;
        },
    }
</script>

<template>
    <div>Car is in {{properties.color}} and has a max speed of {{properties.maxSpeed}}</div>
</template>

但是我的问题是我不知道这是否是正确的方法?会不会给我带来麻烦?还是有更好的方法呢?

第455篇《在Vue.js 2中将道具作为初始数据传递的正确方法是什么?》来自Winter(https://github.com/aiyld/aiyld.github.io)的站点

0个回答

问题类别

JavaScript Ckeditor Python Webpack TypeScript Vue.js React.js ExpressJS KoaJS CSS Node.js HTML Django 单元测试 PHP Asp.net jQuery Bootstrap IOS Android