jQuery get 方法内操控vue变量(异步ajax请求方法中操控双向绑定的响应式变量)实现异步请求函数内完成变量的双向响应式绑定
// 首先,创建一个Vue实例
new Vue({
el: '#app',
data: {
message: 'Hello, Vue!'
},
mounted: function() {
var self = this;
// 使用jQuery发起get请求
$.get('your/api/url', function(data) {
// 当请求成功完成后,更新Vue实例的响应式数据
self.message = data.message;
}).fail(function() {
console.error('Get request failed');
});
}
});
————————————————————————————————————
<html> <head> <meta charset="UTF-8"/> <meta name="viewport" content="width=device-width,initial-scale=1.0"/> <script src="http://127.0.0.1:8080/js/vue.3.5.13.js"></script> <!-- import CSS --> <link rel="stylesheet" href="http://127.0.0.1:8080/css/element-plus@2.9.1.css"> <!-- import JavaScript --> <script src="http://127.0.0.1:8080/js/element-plus@2.9.1.full.js"></script> <script src="http://127.0.0.1:8080/js/axios.1.7.9.min.js"></script> <script src="http://127.0.0.1:8080/js/d3.v7.min.js"></script> <script type="text/javascript" src="http://127.0.0.1:8080/js/jquery_3.7.1.min.js"></script> <script src="http://127.0.0.1:8080/js/echarts_5.5.1.min.js"></script> <title>Element Plus demo</title> </head> <body> <div id="app"> <div> <el-button type="primary" @click="this.getPodinfo">查询</el-button><el-input v-model="myform.name" style="width: 240px" placeholder="Please input"/> </div> <div> <ol> <li v-for="pod in podinfo"> {{ pod.name }} </li> <li> {{myform.name}} </li> <li> {{podinfo.length}} </li> <li>{{testValue}}</li> </ol></div> <div> <el-link href="https://element-plus.org" target="_blank">default</el-link> <el-link type="primary">primary</el-link> <el-link type="success">success</el-link> <el-link type="warning">warning</el-link> <el-link type="danger">danger</el-link> <el-link type="info">info</el-link> </div> <div> 电饭锅 <el-tree style="max-width: 600px" :data="podinfo" :props="defaultProps" @node-click="handleNodeClick" /> </div> <div> {{podinfo.name}} {{testValue}} </div> </div> <script> const App = { data() { return { myform: { name: "" }, podinfo : [], testValue : null, defaultProps : { children: 'children', label: 'name', } }; }, methods: { getPodinfo() { var ROOT_PATH = 'http://127.0.0.1:8080'; var self = this;//这一步是关键,只有这样才能够在ajax异步请求方法中,将请求回来的response数据赋值给vue实例中的双向绑定响应式属性变量 axios.get(ROOT_PATH + '/api/test/podDetail?podName=' + this.myform.name) .then(function (response) { // handle success console.log("测试axios开始"); console.log(response); self.podinfo=[response.data]; console.log(podinfo); self.testValue2='测试值'; console.log("测试axios结束"); }) .catch(function (error) { // handle error console.log(error); }) .finally(function () { // always executed }); $.get(ROOT_PATH + '/api/test/podDetail?podName='+this.myform.name, function (data2) { console.log(data2) self.podinfo=[data2]; self.testValue='测试值3'; console.log("数据") console.log(this.podinfo) }); }, handleNodeClick(){ console.log("点了"); } } }; const app = Vue.createApp(App); app.use(ElementPlus); app.mount("#app"); </script> </body> </html>