一、环境配置
vue create productapp --default
npm install bootstrap@4.0.0
npm install --save core-js
二、源代码
productapp/src/main.js
:
import Vue from 'vue'
import App from './App.vue'
import "../node_modules/bootstrap/dist/css/bootstrap.min.css"
Vue.config.productionTip = false
new Vue({
render: h => h(App),
provide: function () {
return {
eventBus: new Vue()
}
}
}).$mount('#app')
productapp/src/App.vue
:
<template>
<div class="container-fluid">
<div class="row">
<div class="col-8 m-3">
<product-display></product-display>
</div>
<div class="col m-3">
<product-editor></product-editor>
</div>
</div>
</div>
</template>
<script>
import ProductDisplay from "./components/ProductDisplay";
import ProductEditor from "./components/ProductEditor";
export default {
name: "App",
components: { ProductDisplay, ProductEditor }
};
</script>
productapp/src/components/ProductDisplay.vue
:
<template>
<div>
<table class="table table-sm table-striped table-bordered">
<tr>
<th>ID</th><th>Name</th><th>Price</th><th></th>
</tr>
<tbody>
<tr v-for="p in products" v-bind:key="p.id">
<td>{{ p.id }}</td>
<td>{{ p.name }}</td>
<td>{{ p.price }}</td>
<td>
<button class="btn btn-sm btn-primary"
@click="editProduct(p)">
Edit
</button>
</td>
</tr>
</tbody>
</table>
</div>
</template>
<script>
import Vue from "vue";
export default {
data: function () {
return {
products: [
{ id: 1, name: "Kayak", price: 275 },
{ id: 2, name: "Lifejacket", price: 48.95 },
{ id: 3, name: "Soccer Ball", price: 19.50 },
{ id: 4, name: "Corner Flags", price: 39.95 },
{ id: 5, name: "Stadium", price: 79500 }]
}
},
methods: {
editProduct(product) {
this.eventBus.$emit("edit", product);
},
processComplete(product) {
let index = this.products.findIndex(p => p.id == product.id);
if (index == -1) {
return;
} else {
Vue.set(this.products, index, product);
}
}
},
inject: ["eventBus"],
created() {
this.eventBus.$on("complete", this.processComplete);
}
}
</script>
productapp/src/components/ProductEditor.vue
:
<template>
<div>
<div class="form-group">
<label>ID</label>
<input v-model.number="product.id" class="form-control" />
<label>Name</label>
<input v-model="product.name" class="form-control" />
<label>Price</label>
<input v-model.number="product.price" class="form-control" />
</div>
<div class="text-center">
<button class="btn btn-primary" @click="save">Save</button>
<button class="btn btn-secondary" @click="cancel">Cancel</button>
</div>
</div>
</template>
<script>
export default {
data: function() {
return {
product: {}
};
},
methods: {
startEdit(product) {
this.product = {
id: product.id,
name: product.name,
price: product.price
};
},
save() {
this.eventBus.$emit("complete", this.product);
console.log(`Edit Complete: ${JSON.stringify(this.product)}`);
this.product = {}
},
cancel() {
this.product = {};
}
},
inject: ["eventBus"],
created() {
this.eventBus.$on("edit", this.startEdit);
}
};
</script>
网友评论