【IMWeb训练营作业】用Vue做简单的自定义select

来源:互联网 发布:js设置全局cookie 编辑:程序博客网 时间:2024/05/20 09:26

效果图



代码:

<!DOCTYPE html><html lang="en"><head><meta charset="UTF-8"><title>用vue封装自定义组件</title><script src = "https://unpkg.com/vue@2.2.6/dist/vue.js"></script><style>body {  background-color: rgb(232, 232, 232);  font-family: Georgia, "Times New Roman", Times, serif;  font-size: small;  margin: 0px;}section.wrap {  width: 230px;  height: 160px;  background: rgba(252, 174, 152, 0.5);  margin: 20px;  padding: 10px;  -webkit-box-sizing: border-box;  -moz-box-sizing: border-box;  box-sizing: border-box;}h2 {  display: block;  margin: 15px 0 4px;  font-size: 15px;  line-height: 1.4;  letter-spacing: 1px;}.wrap select {  width: 194px;  padding: 16px;  margin: 12px 0px;  border-radius: 5px;  border: 1px solid #b7b6b6;  color: rgb(80, 80, 80);  font-family: Georgia, serif;  font-size: 14px;  letter-spacing: 1px;}</style></head><body><!-- 模板 --><div id="app"><custom-select btn-value="Order" v-bind:list='list1'></custom-select><!-- btn-value是自定义属性,属性名称一般用烤串形式 --><!-- 用v-bind动态绑定自定义属性list --><custom-select btn-value= "Order now!" v-bind:list='list2'></custom-select></div><script>//数据var data = {list1:['Volvo','Saab','Opel',"Audi"],list2:['Apple','Orange','Banana','Lemon','Grape']}//注册组件,要使用自定义组件,要先注册。这里是个全局组件。局部组件把component写在new Vue内Vue.component("custom-select",{ //注意Vue开头要大写,component开头要小写,因为是个functionprops:['btnValue','list'],//注意这里属性命名一定要用驼峰形式。自定义属性list先用v-bind传入父组件custom-select,再用一次v-bind传入到子组件custom-listtemplate:`<section class="wrap"><h2>Please select an item:</h2><custom-list v-bind:list="list"></custom-list><!-- 是custom-select的子组件 --><input type='button' v-bind:value='btnValue' /><!-- value的值和props中的保持一致 --></section>`});//在父组件中定义一个子组件Vue.component('custom-list',{props:['list'],//在子组件生命中也要在props设置一下自定义属性list,否则子组件接收不到template:`<select><option v-for='item of list' v-bind:value='item' >{{item}}</option>//使用v-for循环list中的item。绑定onchange事件,把item传进来,这里是子组件中的交互  <!--<option value ="Volvo">Volvo</option>  <option value ="saab">Saab</option>  <option value="opel">Opel</option>  <option value="audi">Audi</option>--></select>`,/*methods:{//components里面也有methods属性selectValueHandle:function(item){//在子组件里有交互,需要把子组件的值传入父组件中的span元素中,需要自定义事件。而且把父组件的值传入子组件,只需要自定义属性,通过属性名称来传//告知父级,把val属性的值改为item,需要触发一个自定义事件}}*/});//vm,一个文件里可以设置多个new Vuevar vm = new Vue({ //根实例el:"#app",data:data});</script></body></html>


0 0