模板渲染
当前 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” 按钮之后:

                    
                
                
            
        
浙公网安备 33010602011771号