組件
組件 (Component) 是 Vue.js 最強大的功能之一。組件可以擴展 HTML 元素,封裝可重用的代碼。在較高層面上,組件是自定義元素,Vue.js 的編譯器為它添加特殊功能。
組件的作用
組件是對特點功能代碼(html,css,js)的封裝, 通過組件的名字可以重復利用該組件中的代碼.
1全局組件
全局組件的語法:
Vue.component("自定義標簽的名字",{配置對象})
全局組件的特點:
全局組件可以在任何被掛着的標簽中使用.
全局組件的配置對象中必須包含template屬性
代碼演示
1 <div id="app"> 2 <myform></myform> 3 </div>
1 <!-- script必需使用 type=text/template才可以使用--> 2 <script id="mytemp2" type="text/template"> 3 <form action="" method="post"> 4 名稱:<input type="text" name="username" /> <br /> 5 密碼:<input type="password" name="password" /> <br /> 6 <input type="submit" value="提交" /> 7 </form> 8 </script> 9 10 <script> 11 12 //全局組件(任何掛載點都可以使用) 13 Vue.component("myform",{ 14 //如果模板內容太多,寫在這里會很麻煩 15 template:"#mytemp2" 16 }) 17 18 new Vue({ 19 el:"#app", 20 data:{ 21 message:"你好啊!" 22 } 23 }) 24 25 </script>
局部組件
局部語法:
var app = new Vue({
el: "#app",
data: {},
components : {
"局部組件的名字1" : {組件的配置對象}
"局部組件的名字2" : {組件的配置對象}
}
});
局部組件的特點
局部組件只能夠在所掛載的標簽中使用.
1 <div id="app"> 2 <myform></myform> 3 </div>
1 <template id="mytemp"> 2 <div>//模板這個是 3 名稱:<input type="text" name="username" /> <br /> 4 密碼:<input type="password" name="password" /> <br /> 5 <input type="submit" value="提交" @click="say" /> 6 </div> 7 </template> 8 9 <script> 10 11 new Vue({ 12 el:"#app", 13 data:{ 14 15 }, 16 components:{ 17 //只有當前的掛載點使用 18 myform:{ 19 template:"#mytemp", 20 //這個data必需是一個函數 21 data() { 22 return { 23 count: 0, 24 message:"我也是一個中國人" 25 } 26 }, 27 methods:{ 28 say(){ 29 alert("點我啊"); 30 } 31 } 32 } 33 } 34 }) 35 36 </script>
路由
路由是負責將進入的瀏覽器請求映射到特定的 組件 代碼中。 即決定了由誰(組件)去響應客戶端請求。簡單說路由就是url地址和對應的資源(組件)的映射,通過一個路徑的url地址,可以唯一找到一個資源。路由不包含在vue中,是一個插件,需要單獨下載。
官方地址:https://router.vuejs.org/zh/
路由的使用
1 <div id="app"> 2 <p> 3 <!-- 4 router-link:路由標簽(它就是一個a標簽) 5 to="/foo":路徑(到哪里雲) 6 --> 7 <router-link to="/main">首頁</router-link> 8 <router-link to="/singer">歌手</router-link> 9 <router-link to="/hot">熱門歌曲</router-link> 10 </p> 11 <!-- 路由出口 --> 12 <!-- 路由匹配到的組件將渲染在這里 --> 13 <router-view></router-view> 14 </div> 15 16 17 <script> 18 19 // 2. 定義路由 20 // 每個路由應該映射一個組件。 其中"component" 可以是 21 // 通過 Vue.extend() 創建的組件構造器, 22 // 或者,只是一個組件配置對象。 23 // 我們晚點再討論嵌套路由。 24 var routes = [ 25 { 26 path: '/main', 27 component: { 28 template:"<h2>我是主頁我怕誰</h2>" 29 } 30 }, 31 { 32 path: '/singer', 33 component: { 34 template:"<h2>我是歌手第5季</h2>" 35 } 36 }, { 37 path: '/hot', 38 component: { 39 template:"<h2>葫蘆娃</h2>" 40 } 41 } 42 ] 43 44 //定義一個路由 45 var router = new VueRouter({ 46 routes // (縮寫) 相當於 routes: routes 47 }) 48 49 new Vue({ 50 el:"#app", 51 router:router 52 }) 53 54 </script>