要在 uniapp 中嵌入在线网页 vue 代码并执行 js 脚本,可以使用 uni-app 提供的 web-view 组件。

1. 在 uniapp 项目中创建一个 web-view 组件,例如:

<template>
  <view>
    <web-view :src='url' @message='onMessage'></web-view>
  </view>
</template>

<script>
export default {
  data() {
    return {
      url: 'http://example.com/vue.html'
    }
  },
  methods: {
    onMessage(e) {
      // 在这里处理从 web-view 中发送的消息
      console.log(e.detail.data)
    }
  }
}
</script>

2. 在 vue.html 中编写 vue 代码和 js 脚本,例如:

<!DOCTYPE html>
<html>
<head>
  <meta charset='UTF-8'>
  <title>Vue Example</title>
  <script src='https://cdn.jsdelivr.net/npm/vue/dist/vue.js'></script>
</head>
<body>
  <div id='app'>
    <p>{{ message }}</p>
  </div>
  <script>
    var app = new Vue({
      el: '#app',
      data: {
        message: 'Hello Vue!'
      },
      mounted: function() {
        // 在这里执行 js 脚本
        console.log('mounted')
      }
    })
  </script>
</body>
</html>

3. 在 uniapp 中使用 web-view 组件加载 vue.html,例如:

<template>
  <view>
    <web-view :src='url' @message='onMessage'></web-view>
  </view>
</template>

<script>
export default {
  data() {
    return {
      url: 'http://example.com/vue.html'
    }
  },
  methods: {
    onMessage(e) {
      // 在这里处理从 web-view 中发送的消息
      console.log(e.detail.data)
    }
  }
}
</script>

这样就可以在 uniapp 中嵌入在线网页 vue 代码并执行 js 脚本了。在 web-view 中发送消息可以使用 postMessage 方法,例如:

mounted: function() {
  // 发送消息到 uniapp 中
  window.parent.postMessage({ data: 'hello uniapp' }, '*')
}
uniapp 嵌入在线网页 vue 代码并执行 js 脚本

原文地址: https://www.cveoy.top/t/topic/lc0W 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录