这里做了一个全局的组件vue.component('mycomp',{})
在中写组件,将id=comp1
script中直接template:"#copm1"
其他的部分就是之前所讲的watch来实现简易计算器差不多
<div id="app">
<hr>
<mycomp>mycomp>
div>
<template id="comp1">
<div>
<h1>组件watch监听-计算(CQNU-ZJW)h1>
<input type="text" v-model.number="obj.pre">
<p v-model="obj.type">+p>
<input type="text" v-model.number="obj.next">=
<input type="text" v-model.number="obj.result">
div>
template>
<script>
var com=Vue.component('mycomp',{
template:"#comp1",
data(){
return {
obj: {
pre: 1,
type: "+",
next: 1,
result: 2,
}
}
},
methods:{},
watch:{
"obj": {
handler(nval, oval) {
// 只要obj发生变化重新计算result的值
this.obj.result = eval(`${this.obj.pre}${this.obj.type}${this.obj.next}`)
},
deep: true,
}
}
})
new Vue({
el:'#app',
data:{
}
})
script>
其实都大差不差可以理解的,我在此就不再赘述了。注意理解项目结构,注意再vue项目中组件是通过import
载入就行
<template>
<div id="app">
<img alt="Vue logo" src="./assets/logo.png">
<comp1/>
div>
template>
<script>
/*import HelloWorld from './components/HelloWorld.vue'*/
import comp1 from './components/comp1.vue'
export default {
name: 'App',
components: {
/*HelloWorld*/
comp1
}
}
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>
<template>
<div calss="hello">
<h1>{{ msg }}h1>
<input type="text" v-model.number="obj.pre">
<p v-model="obj.type">+p>
<input type="text" v-model.number="obj.next">=
<input type="text" v-model.number="obj.result">
div>
template>
<script>
export default {
name: "comp1",
props: {
msg: String
},
data(){
return {
obj: {
pre: 1,
type: "+",
next: 1,
result: 2,
}
}
},
watch:{
"obj": {
handler(nval, oval) {
// 只要obj发生变化重新计算result的值
this.obj.result = eval(`${this.obj.pre}${this.obj.type}${this.obj.next}`)
},
deep: true,
}
}
}
script>
<style scoped>
style>
然后npm run serve
启动项目,浏览器输入http://localhost:8080/#/
即可