Vue - x-template

  • 1981
  • 0
  • Vue
  • 2019-04-23

1.使用 x-template 來開發元件 寫法一

2.使用 x-template 來開發元件 寫法二

3.在template裡面宣告變數注意事項

<div id="app">
  <table class="table">
    <thead>
    </thead>
    <tbody>
      <tr v-for="(item, key) in data" :item="item" :key="key">
        <td>{{ item.name }}</td>
        <td>{{ item.cash }}</td>
        <td>{{ item.icash }}</td>
      </tr>
    </tbody>
  </table>
</div>

上面是很一般使用v-for產生資料表的語法,現在要使用x-template來重購tr

1.使用 x-template 來開發元件 寫法一(全域註冊)

Vue.component 是註冊在所有的Vue應用程式下,這種寫法

所有的Vue應用程式都可以使用這個component

<div id="app">
 <table class="table">
  <thead>
  </thead>
  <tbody>	
    <!--重點1 :person 綁定要傳入的參數-->
    <!--重點2 使用is來動態置換(掛載)component 
	    因為在tbody這個標籤內只能放tr,放其他標籤會錯 
 	-->	
    <tr is="row-component" v-for="(item,index) in data" :person="item" :key="index"></tr>
  </tbody>
 </table>
</div>

<script type="text/x-template" id="rowComponentTemplate">
 <tr>
  <!--重點3 :person 綁定要傳入的參數-->
  <td>{{ person.name }}</td>
  <td>{{ person.cash }}</td>
  <td>{{ person.icash }}</td>
 </tr>
</script>

<script>
// 註冊在所有的Vue.component底下,所有的Vue都可以使用
Vue.component('row-component', {
	props: ['person'], //使用 prop 傳遞資料(要傳入template內的的參數)
	template: '#rowComponentTemplate' //綁定x-template的id
});

 

2.第二種寫法(局部註冊),修改上面的第一種寫法

將component註冊再Vue裡面

<div id="app">
 <table class="table">
  <thead>
  </thead>
  <tbody>	
    <!--重點1 :person 綁定要傳入的參數-->
    <!--重點2 使用is來動態置換component 
	    因為在tbody這個標籤內只能放tr,放其他標籤會錯 
 	-->	
    <tr is="row-component" v-for="(item,index) in data" :person="item" :key="index"></tr>
  </tbody>
 </table>
</div>

<script type="text/x-template" id="rowComponentTemplate">
 <tr>
  <!--重點3 :person 綁定要傳入的參數-->
  <td>{{ person.name }}</td>
  <td>{{ person.cash }}</td>
  <td>{{ person.icash }}</td>
 </tr>
</script>

<script>
// Vue.component('row-component', {
//  props: ['person'],
//  template: '#rowComponentTemplate'
// });

//重點:改宣告一個物件,屬性內容跟原本宣告再component裡面的屬性一樣
var child = {
  props: ['person'], //重點:注意屬性prop"s"
  template: "#rowComponentTemplate"
}

var app = new Vue({
el: '#app',
data: {
data: [{
	name: '小明',
	cash: 100,
	icash: 500,
}, {
	name: '杰倫',
	cash: 10000,
	icash: 5000,
}, {
	name: '漂亮阿姨',
	cash: 500,
	icash: 500,
}, {
	name: '老媽',
	cash: 10000,
	icash: 100,
}, ],
//重點:新增屬性components,將上面宣告的物件綁定在屬性'row-component'
components: {
	'row-component': child
}
}
});
</script>


3.在template裡面宣告變數注意事項

如果在template裡面要宣告變數,要使用function,並且return值

<script>
// Vue.component('counter-component', {
//     data: function() {
//         return {
//             counter: 0
//         };
//     },
//     template: '#counter-component'
// })

var child = {
	data: function() {
		return {
			counter: 0
		};
	},
	template: '#counter-component'
}

var app = new Vue({
	el: '#app',
	components: {
		'counter-component': child
	}
});
</script>