一直想寫一個Vuejs的系列的博客,苦於一直沒有時間,今天的這個博客也是思考了很久,打算隨便寫點東西,今天說說Vuejs的模版的使用。
Vue模版的使用方法
1. 直接使用Html
<div id="container"> <mytemp></mytemp> </div> <script src="vue.min.js"></script> <script> Vue.component('mytemp', { template: ' <h1>Hello I am Temple</h1>', }) new Vue().$mount("#container"); </script>
2. 使用標籤
<div id="container"> <mytemp></mytemp> </div> <script id="temp1" type="x-template"> <h1>Hello I am Temple</h1> </script> <script src="vue.min.js"></script> <script> Vue.component('mytemp', { template: '#temp1' }) new Vue().$mount("#container"); </script>
3. 使用template標籤
<div id="container"> <mytemp></mytemp> </div> <template id="temp1"> <h1>Hello I am Temple</h1> </template> <script src="vue.min.js"></script> <script> Vue.component('mytemp', { template: '#temp1' }) new Vue().$mount("#container"); </script>
局部模版
上面我們使用的全局模版,這個模版可以在所有的vue對象中使用,如果我們僅僅想讓在當前的vue中生效,就要用局部的模版註冊
<div id="container"> <mytemp></mytemp> </div> <template id="temp1"> <h1>Hello I am Temple</h1> </template> <script src="vue.min.js"></script> <script> new Vue({ components: { 'mytemp': { template: '#temp1' } } }).$mount("#container"); </script>
模版的傳值
單項傳遞
對於我們的傳值,我們可以看成父模版向子模版傳值,其中vue是父對象,template是子對象,這裏我們需要使用props屬性,修改我們的額demo如下:
<div id="container"> <mytemp v-bind:myname="name"></mytemp> </div> <template id="temp1"> <h1>Hello I am Temple</h1> </template> <script src="vue.min.js"></script> <script> new Vue({ data: { name: "Vue" }, components: { 'mytemp': { template: '#temp1', props: ["myname"] } } }).$mount("#container"); </script>
注意:props這裏儘量使用小寫字段,駝峯命名需要轉化成-
雙向傳遞
<div id="container"> <mytemp v-bind:myname.sync="name"></mytemp> <h1></h1> </div> <template id="temp1"> <input type="" name="" v-model="myname" /> </template> <script src="vue.min.js"></script> <script> new Vue({ data: { name: "Vue" }, components: { 'mytemp': { template: '#temp1', props: ["myname"] } } }).$mount("#container"); </script>
(本文完)
作者:老付 如果覺得對您有幫助,可以下方的訂閱,或者選擇右側捐贈作者,如果有問題,請在捐贈後諮詢,謝謝合作 如有任何知識產權、版權問題或理論錯誤,還請指正。 自由轉載-非商用-非衍生-保持署名,請遵循:創意共享3.0許可證 交流請加羣113249828:點擊加羣 或發我郵件 [email protected]