如何在 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/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/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