vue.js 单文件组件


1. 工具安装

1. 安装npm

npm全称为Node Package Manager 是一个机遇Node.js的包管理器, 也是整个Node.js 社区最流行、支持第三方模块最多的包管理器 npm -v

2. 由于网络原因,安装cnpm

npm install -g cnpm --registry=https://registry.npm.taobao.org

3. 安装vue-cli

cnpm install -g @vue/cli

4. 安装webpack

cnpm install -g webpack webpack 是 JavaScript 打包器(Module bundler)

5. 图形管理界面

子命令行界面输入 vue ui 在 Vue 项目管理器 创建一个test项目

2.导入到HbuilderX

在HbuilderX 中点击文件--导入--从本地目录导入

导入test 项目后,点击HelloWord.vue 文件 选择运行--运行到浏览器--firefox

3.项目文件介绍

  • 新建自己的组件文件

test.vue

<template>
    <h2 class="red"> {{ msg }}</h2>
</template>

<script>
    export default {

        name: 'test',
        props: {
            msg: {
                type: String,
                default: "test msg"
            }
        },
        methods:{

        },
        data() {
            return {

            }
        },
    }
</script>

<style>
    .red{color: #ff0000;}
</style>

HelloWorld.vue

<template>
  <div class="hello">
    <h1>{{ msg }}</h1>
  </div>
</template>

<script>
export default {
  name: 'HelloWorld',
  props: {
    msg: String
  }
}
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>
h3 {
  margin: 40px 0 0;
}
ul {
  list-style-type: none;
  padding: 0;
}
li {
  display: inline-block;
  margin: 0 10px;
}
a {
  color: #42b983;
}
</style>

.vue 文件的结构是

<-! 包含以下三个部分></-!>
<template></template>
<script></script>
<style></style>

App.vue

<template>
  <div id="app">
    <img alt="Vue logo" src="./assets/logo.png">
    <HelloWorld msg="Welcome to Your Vue.js App"/>
    <test msg="你好,vue.js!"></test> <!-- 使用test标签 -->
    <test></test>
  </div>
</template>

<script>
import HelloWorld from './components/HelloWorld.vue'
import test from './components/test.vue'  //引入我的单文件组件test.vue

export default {
  name: 'App',
  components: {
    HelloWorld,
    test //引入我的组件名称
  }
}
</script>

<style>
#app {
  font-family: Avenir, Helvetica, Arial, sans-serif;
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
  text-align: center;
  color: #2c3e50;
  margin-top: 60px;
}
</style>