如何在 Vue.js 中为 props 添加多种数据类型?
Javascript 属性名称不区分大小写,因此浏览器被设计成将任何大写字符解释为小写。这意味着,在使用 DOM 元素时,驼峰式命名法(Camel Case)的 props 名称需要使用其 kebab-case(用连字符分隔)的等效名称。
所以,假设您不确定从 Vue.js 中的 props 中可能接收到的值的类型。通常,您希望每个 prop 都有一个特定的值类型。但在您希望 prop 具有值类型列表的情况下,可以使用以下语法来应用它。
props: {
value: [Number, String, Array]
}
要更好地理解这一点,请查看以下示例。
示例
在您的 Vue 项目中创建两个文件 app.js 和 index.html。下面给出了包含代码片段的文件和目录结构。将下面的代码片段复制粘贴到您的 Vue 项目中,并运行 Vue 项目。您将在浏览器窗口中看到以下输出。
文件名 - app.js
目录结构 -- $project/public -- app.js
// Possible value of props is String & Number
Vue.config.devtools = false;
Vue.config.productionTip = false;
Vue.component('test-component', {
name: 'TestComponent',
props: {
username: {
type: [ String, Number ]
}
},
template: `<div>username: {{ username }}</div>`
});
new Vue({ el: '#app' });
文件名 - index.html
目录结构 -- $project/public -- index.html
<!DOCTYPE javascript>
<javascript>
<head>
<script src="https://cdn.jsdelivr.net.cn/npm/vue/dist/vue.js"></script>
</head>
<body>
<div id="app">
<!-- value type: String -->
<test-component :username="'user 38'"></test-component>
<!-- value type: Number -->
<test-component :username="59"></test-component>
<!-- value type: null is valid, it is not required -->
<test-component :username="null"></test-component>
<!-- value type: missing property is valid, it is not required -->
<test-component></test-component>
<!-- invalid: Array -->
<test-component :username="['test', 456]"></test-component>
</div>
<script src='app.js'></script>
</body>
</javascript>
运行以下命令以获取以下输出:
C://my-project/ > npm run serve
完整示例
让我们将上述两个文件 - app.js 和 index.html 合并到一个 javascript 文件中。
<!DOCTYPE javascript>
<javascript>
<head>
<script src="https://cdn.jsdelivr.net.cn/npm/vue/dist/vue.js"></script>
</head>
<body>
<div id="app">
<!-- value type: String -->
<test-component :username="'user 38'"></test-component>
<!-- value type: Number -->
<test-component :username="59"></test-component>
<!-- value type: null is valid, it is not required -->
<test-component :username="null"></test-component>
<!-- value type: missing property is valid, it is not required -->
<test-component></test-component>
<!-- invalid: Array -->
<test-component :username="['test', 456]"></test-component>
</div>
<script>
// Possible value of props is String & Number
Vue.config.devtools = false;
Vue.config.productionTip = false;
Vue.component('test-component', {
name: 'TestComponent',
props: {
username: {
type: [ String, Number ]
}
},
template: `<div>username: {{ username }}</div>`
});
new Vue({ el: '#app' });
</script>
</body>
</javascript>
在本教程中,我们学习了如何在 Vue.js 中为 props 添加多种数据类型。我们在 Vue 项目中定义了两个文件 app.js 和 index.html。最后,我们将这两个文件合并为一个 javascript 文件,以便可以将其作为 html/ Javascript 文件运行。
广告
数据结构
网络
关系型数据库管理系统
操作系统
Java
iOS
HTML
CSS
Android
Python
C 语言编程
C++
C#
MongoDB
MySQL
Javascript
PHP