组件:基础的基础
知识点
- 组件(Component,Portlet)
组件
组件就是页面上的一小块区域内容,完成一个小的页面功能,请参照视频第六课。
综合例
<div id="myApp">
<today-weather></today-weather>
</div>
<script>
Vue.component('today-weather', {
template: '<div>今天下雨,出不去啦,干什么呢?看Youtube吧!</div>'
});
var myApp = new Vue({
el: '#myApp',
});
</script>
显示:
组件:局部的组件
知识点
- 组件的局部注册
组件
Vue.js的组件不仅可以单独声明注册使用,还可以在Vue实例中进行局部注册使用。
综合例
<div id="myApp">
<my-weather></my-weather>
</div>
<script>
var WeatherComponent = {
template: '<div>今天下雨,随它去吧!</div>'
};
var myApp = new Vue({
el: '#myApp',
data: {
},
components: {
'my-weather': WeatherComponent
},
});
</script>
显示:
组件:表行组件
知识点
- 制作表行组件
表行组件
为自己的页面表格编写表行组件。
综合例
<div id="myApp">
<h1>2017年最期待的游戏是:</h1>
<table border="1">
<tr>
<td>编号</td>
<td>游戏名称</td>
</tr>
<my-row1></my-row1>
<my-row2></my-row2>
<my-row3></my-row3>
</table>
</div>
<script>
Vue.component('my-row1', {
template: '<tr><td>(1)</td><td>塞尔达传说:荒野之息(3/3)</td></tr>'
});
Vue.component('my-row2', {
template: '<tr><td>(2)</td><td>新马里奥赛车(4/28)</td></tr>'
});
Vue.component('my-row3', {
template: '<tr><td>(3)</td><td>喷射乌贼娘2代</td></tr>'
});
var myApp = new Vue({
el: '#myApp',
data: {
},
methods: {
},
});
</script>
显示:
组件:数据
知识点
- 组件的数据函数
组件的数据
为Vue.js组件添加数据,使组件可以动态显示各种数据,注意是数据函数,不是数据属性。
综合例
<div id="myApp">
<div>今天的天气是<today-weather/></div>
</div>
<script>
Vue.component('today-weather', {
template: '<strong>{{todayWeather}}</strong>',
data: function(){
return {
todayWeather: '雨加雪'
};
}
});
var myApp = new Vue({
el: '#myApp',
});
</script>
显示:
组件:传递数据
知识点
- 为组件传递数据
组件数据传递
制作可接受参数的组件。
综合例
<div id="myApp">
<h1>您的成绩评价</h1>
<test-result :score="50"></test-result>
<test-result :score="65"></test-result>
<test-result :score="90"></test-result>
<test-result :score="100"></test-result>
</div>
<script>
Vue.component('test-result', {
props: ['score'],
template: '<div><strong>{{score}}分,{{testResult}}</strong></div>',
computed: {
testResult: function() {
var strResult = "";
if (this.score < 60)
strResult = "不及格";
else if (this.score < 90)
strResult = "中等生";
else if (this.score <= 100)
strResult = "优秀生";
return strResult;
}
}
});
var myApp = new Vue({
el: '#myApp',
});
</script>
显示:
组件:传递变量
知识点
- 为组件传递变量数据
组件的数据
制作可接受变量参数的组件。
综合例
<div id="myApp">
<div>请输入您的名字:<input v-model="myname"></div>
<hr/>
<say-hello :pname="myname" />
</div>
<script>
Vue.component('say-hello', {
props: ['pname'],
template: '<div>你好,<strong>{{pname}}</strong>!</div>',
});
var myApp = new Vue({
el: '#myApp',
data: {
myname: 'Koma'
}
});
</script>
显示: