前言
在使用Vue的自定義元件的功能時,出現了一個錯誤
vue.js:634 [Vue warn]: Unknown custom element: <student> - did you register the component correctly? For recursive components, make sure to provide the "name" option.
代碼如下
- html
<body> <div id="div"> <student myname="不知火舞" age="24" sex="女"></student> </div> </body>
- js
//建立vue對象 new Vue({ //指定此vue對象解析的模闆區域 el: "#div" }); //自定義student标簽元件 Vue.component("student", { //定義元件的屬性 props: ["myname", "age", "sex"], //定義元件的資料 data: function () { return { school: "清華中學" } }, //定義此元件的底層模闆 template: ` <div> <div>{{myname}}</div> <div>{{age}}</div> <div>{{sex}}</div> </div> ` });
- js解釋
- component( ):此方法是
Vue
用于自定義元件的方法。
參數1:指定自定義元件的元件名。
參數2:配置元件的參數屬性。
- props:配置元件的屬性,每個元件可以配置多個屬性,多個屬性使用數組包裝。
- data:配置元件的資料,可以在元件模闆中使用定義好的資料。
- template:配置此元件的底層模闆,可以在此模闆中使用插值表達式,引用前面配置的屬性和資料。
- component( ):此方法是
錯誤解決
将建立Vue對象和自定義元件的代碼交換以下即可,要先定義元件,再建立Vue對象。
//自定義student标簽元件
Vue.component("student", {
//定義元件的屬性
props: ["myname", "age", "sex"],
//定義元件的資料
data: function () {
return {
school: "清華中學"
}
},
//定義此元件的底層模闆
template: `
<div>
<div>{{myname}}</div>
<div>{{age}}</div>
<div>{{sex}}</div>
<div>{{school}}</div>
</div>
`
});
//建立vue對象
new Vue({
//指定此vue對象解析的模闆區域
el: "#div"
});