您的位置:首页 > Web前端 > Vue.js

初始化一个vue项目

2021-12-05 14:40 429 查看

前言

初始化

  • 参考这篇博客构建一个最简单的vue项目
  • 启动项目后报错:
    errors and 0 warnings potentially fixable with the --fix option.
  • 解决方案:配置项目根目录下的package.json
"lint": "eslint --fix --ext .js,.vue src",
  • 自定义一个组件,添加到根组件后,启动项目报错:
    Module Error (from ./node_modules/eslint-loader/index.js):
  • 解决方案:项目根路径下新建
    vue.config.js
module.exports = {
lintOnSave: false
}

基础使用

  • 自定义组件
# 在components目录下新建一个子组件 UserList.vue
<template>
<div>
Hello!!
</div>
</template>

<script>
export default {

}
</script>
  • 根组件中导入该子组件并使用
<template>
<div>
<user-list/>
</div>
</template>

<script>
import UserList from './components/UserList.vue'
export default {
name: 'App',
components: {
UserList,
}
}
</script>
  • 页面渲染
<template>
<div>
<!-- 使用子组件 -->
<user-list/>
<!-- 声明式渲染 -->
{{msg}}
<!-- 双向绑定 -->
<div id="two-way-binding">
<p>{{ message }}</p>
<input v-model="message" />
</div>
<!-- v-if -->
<div id="conditional-rendering">
<span v-if="seen">现在你看到我了</span>
</div>
<!-- v-for -->
<div id="list-rendering">
<ol>
<li v-for="todo in todos">
{{ todo.text }}
</li>
</ol>
</div>
</div>
</template>

<script>
import UserList from './components/UserList.vue'
export default {
name: 'App',
components: {
UserList,   // 子组件
},
data() {
return {
msg: '文本',    // 声明式渲染
message: 'Hello Vue!',     // 双向绑定
seen: true,   // v-if
todos: [
{ text: 'Learn JavaScript' },
{ text: 'Learn Vue' },
{ text: 'Build something awesome' }
]   // v-for
}
},
created(){
console.log("生命周期!")
}
}
</script>
  • 指令及其缩写
<template>
<div>
<!-- v-bind -->
<a v-bind:href="myUrl" v-bind:title="myTitle" v-bind:id="myId">这是a标签</a><br>
<!-- v-bind缩写 -->
<a :href="myUrl">v-bind的缩写</a><br>
<!-- v-on -->
<input type="text" v-on:blur="myBlur"><br>
<!-- v-on缩写 -->
<button @click="mySubmit">v-on的缩写:v-on:替换成@</button>
</div>
</template>

<script>
export default {
data(){
return {
myUrl: 'www.baidu.com'
,myTitle: '这是title_2'
,myId: 'id2'
,myUrl: 'https://www.baidu.com/'
}
},
methods: {
myBlur(){
console.log("失去焦点!");
},
mySubmit(){
console.log("阻止提交!")
}
}
}
</script>
  • 侦听器
<template>
<div>
<input type="text" v-model="msg"><br>
<input type="text" v-model="name">
</div>
</template>

<script>
export default {
data() {
return {
msg: '',
name: ''
}
},
watch: {
msg(oldValue,newValue){
console.log("oldValue:", oldValue, ",newValue:", newValue);
}
,name(oldval,newval){
console.log("oldval:", oldval, ",oldval:", oldval)
this.getUser(newval)  //调用方法
}
},
methods: {
getUser(name){
// 发送请求的方法,这里结合侦听器使用
console.log("name:", name)
}
}
}
</script>
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: