在JavaScript中使用Vue组件数据



我们应该如何从应用程序外部访问Vue组件的数据?例如,我们如何从Vue应用程序外部DOM中的按钮触发的常规JavaScript onClick事件中获取数据?

在下面的设置中,我有一个隐藏的字段,我在Vue应用程序中的每个动作都保持更新,这样我就有必要的数据为JS点击事件做好准备。但我相信有更好的办法。

当前我的设置如下:

VehicleCertificates.js

import { createApp, Vue } from 'vue'
import VehicleCertificates from './VehicleCertificates.vue';
const mountEl = document.querySelector("#certificates");
const app = createApp(VehicleCertificates, { ...mountEl.dataset })
const vm = app.mount("#certificates");

VehicleCertificates.vue

<template>
<div style="background-color: red;">
<h3>Certificates</h3>
<div>
<table class="table table-striped table-hover table-condensed2" style="clear: both;">
<thead>
<tr>
<th><b>Type</b></th>
<th><b>Valid From</b></th>
<th><b>Valid Till</b></th>
<th style="text-align: right;">
<a href="#" @click='addCertificate'>
<i class="fa fa-plus-square"></i> Add
</a>
</th>
</tr>
</thead>
<tbody>
<tr v-for="(certificate, index) in certificates" :key="index">
<td>{{ certificate.CertificateTypeDescription }}</td>
<td>
{{ certificate.ValidFrom }}
</td>
<td>
{{ certificate.ValidTo }}
</td>
<td>
<a href='#' @click="removeCertificate(index)" title="Delete" style="float: right;" class="btn btn-default">
<i class="fa fa-trash"></i>
</a>
</td>
</tr>
<tr v-show="certificates.length == 0">
<td colspan="4">
No certificates added
</td>
</tr>
</tbody>
</table>
</div>
</div>
</template>
<script>
import axios from 'axios';
import { onMounted, ref } from "vue";
export default {
props: {
vehicleId: String
},
data() {
return {
count: 0,
certificates: ref([]),
types: []
}
},
created() {
onMounted(async () => {
let result = await axios.get("/api/v1.0/vehicle/GetCertificates", { params: { vehicleId: this.vehicleId } });
this.certificates.splice(0, 0, ...result.data);
this.certificatesUpdated();
});
},
methods: {
removeCertificate(index) {
this.certificates.splice(index, 1);
this.certificatesUpdated();
},
addCertificate() {
this.certificates.push({ CertificateTypeDescription: 'ADR', ValidFrom: 1, ValidTo: 2 });
this.certificatesUpdated();
},
certificatesUpdated() {
$("#VehicleCertificatesJson").val(JSON.stringify(this.certificates));
}
}
}
</script>

最后,我希望能够从Vue应用程序发送的数据与其他非Vue数据一起提交的ASP。网芯剃刀页面其形式。Vue应用程序只是razor视图的一个特定部分,因此不是SPA。

提前感谢!

这是一个相当复杂的解决方案-但至少它是相当灵活的。

  1. 创建一个Vue.observablestore:这是一个响应对象
  2. 创建您想要使用的方法来更新Vue实例中的observable
  3. 添加watcher到存储:这是一个标准的Vue对象&a$watchset on it
  4. 设置回调,如果store改变(watcher实例):这个回调是你可以与"外部世界"连接的地方。

片段:

const countervalueSpan = document.getElementById('countervalue')
// creating a Vue.observable - 
// reactive object
const store = Vue.observable({
counter: 0
})
// setting up a watcher function
// using the Vue object
function watch(obj, expOrFn, callback, options) {
let instance = null
if ('__watcherInstance__' in obj) {
instance = obj.__watcherInstance__
} else {
instance = obj.__watcherInstance__ = new Vue({
data: obj
})
}
return instance.$watch(expOrFn, callback, options)
}
// creating a watcher that reacts
// if the given store item changes
const subscriber = watch(
store,
'counter',
(counter) => {
let html = `<strong>${counter}</strong>`
countervalueSpan.innerHTML = html
}
)
new Vue({
el: "#app",
methods: {
increment() {
store.counter++
}
},
template: `
<div>
<button
@click="increment"
>
INCREMENT
</button>
</div>
`
})
<script src="https://cdn.jsdelivr.net/npm/vue@2.6.14/dist/vue.js"></script>
<div id="outside">
Counter outside: <span id="countervalue"></span>
</div>
<div id="app"></div>

你总是可以很容易地从外部访问store对象(例如store.counter) &你总是得到对象的当前状态。需要监视器自动对变化作出反应。

我建议不要这样做,在Vue中包装一切或直接使用JQuery,这取决于你的网站是如何构建的。拥有多个前端框架通常不是一个好主意,会带来不必要的复杂性。

但是,如果你真的需要用纯javascript访问Vue的数据,你可以使用以下命令:

const element = document.getElementById('#element-id');
element._instance.data // or element._instance.props, etc...

对于可用的属性,您可以查看检查器(见附带的截图)。检查员截图

最新更新