模板渲染
當前 App.vue :
<template> <div> 我來自App.vue </div> </template>
頁面表現:
組件通信
Vue 的單文件組件通過一個類似HTML文件的.vue文件就能描述清楚一個組件所需的模板、樣式、邏輯。
在 components 目錄下新建 SayHi.vue (組件使用大駝峰命名法)。
編寫 SayHi.vue, 代碼:
<template> <div> 我來自SayHi.vue </div> </template>
編寫 App.vue,代碼:
<template> <div> 我來自App.vue <say-hi/> </div> </template> <script> import SayHi from "./components/SayHi"; export default{ name: "App", components: { SayHi } } </script>
頁面表現:
在 SayHi.vue 聲明變量並且渲染變量,代碼:
<template> <div> 我來自SayHi.vue <p>{{ message }}</p> </div> </template> <script> export default { data() { return { message: 'Hello~俺是小許' } } } </script>
頁面表現:
樣式描述
在 App.vue 添加樣式,代碼:
<template> <div id="sty1"> 我來自App.vue <say-hi/> </div> </template> <script> import SayHi from "./components/SayHi"; export default{ name: "App", components: { SayHi } } </script> <style> #sty1{ width: 200px; height: 200px; background-color: pink; } </style>
頁面表現:
在 SayHi.vue 里添加樣式,代碼:
<template> <div class="sty2"> 我來自SayHi.vue <p>{{ message }}</p> </div> </template> <script> export default { data() { return { message: 'Hello~俺是小許' } } } </script> <style> .sty2{ width: 150px; height: 100px; background-color: rgb(177, 120, 231); color: white; } </style>
頁面表現:
export default
Q: 在前面組件邏輯里有看到 export default{ ... },它的作用是什么呢?
A: 方便其它代碼對這個代碼進行引用
下面 2 段代碼是相同的,左邊是 ES6 的簡寫。
![]()
|
![]()
|
補充
在 SayHi.vue 中聲明變量並調用方法,代碼:
<template> <div class="sty2"> 我來自SayHi.vue <p>{{ message }}</p> <button @click="show_my_value()">U•ェ•*U</button> </div> </template> <script> export default { data() { return { message: 'Hello~俺是小許', my_value : 'who r u?' } }, methods: { show_my_value: function(){ alert('😜' + this.my_value); } } } </script> <style> .sty2{ width: 150px; height: 100px; background-color: rgb(177, 120, 231); color: white; } </style>
頁面表現:
點擊 “U•ェ•*U” 按鈕之后: