为了账号安全,请及时绑定邮箱和手机立即绑定

动态地将组件标记传递给 Vue 实例

动态地将组件标记传递给 Vue 实例

江户川乱折腾 2024-01-22 16:53:32
var customerID = "cus_1234xxx..."; // Retrieved from session or DBvar options = new ChargeListOptions { Limit = 3, Customer = customerID };var service = new ChargeService();StripeList<Charge> charges = service.List(  options);希望这能说明问题!我目前正在构建一些软件,它允许用户将 HTML 片段放入网页中,并且我的 VueJS 堆栈将动态呈现博客文章。我正在尝试找到一种方法来动态地将组件标记渲染到给定中,<div>而无需在其中声明 Vue 组件标记<div>- 以避免客户感到困惑。这是工作代码的示例:<div id="live-blogs" v-cloak>    <live-blog        v-for="blog in blogs"        :key="blog.id"        :title="blog.title"    ></live-blog></div>Vue.component('live-blog', {    props: ['id', 'title'],    template: '<div class="lb-entry">{{ title }}</div>',});const liveBlogs = new Vue({    el: '#live-blogs',    data: {        blogs: [],    },    methods: {        getLiveBlogs: function() {            request.get('/read/' + id)                .then(function (response) {                    liveBlogs.blogs = response.data.data;                })        }    },    mounted() {        this.getLiveBlogs();    }});我想做的事我希望能够删除组件标记,以便我的客户只需复制并粘贴以下代码。我可能会添加更多组件和功能,并且不希望此嵌入的大小不断增大。一旦检测到目标<div>,JavaScript 就应该处理组件数据的动态注册和渲染。<div id="live-blogs"></div><script type="text/javascript" src="/path/to/file/app.js"></script>到目前为止我已经尝试过的我尝试过通过传递组件标记,this.$el.innerHTML = componentMarkup但没有成功。使用 VueJS 可以吗?
查看完整描述

1 回答

?
芜湖不芜

TA贡献1796条经验 获得超7个赞

您所需要做的就是将模板作为字符串模板从 DOM 移动到主组件中。只要<div id="live-blogs"></div>页面上有某个地方,它就可以工作。


Vue.component('live-blog', {

  props: ['id', 'title'],

  template: '<div class="lb-entry">{{ title }}</div>',

});


new Vue({

  el: '#live-blogs',

  template: `

<div>

  <live-blog

    v-for="blog in blogs"

    :key="blog.id"

    :title="blog.title"

  />

</div>`,

  data() {

    return {

      blogs: [],

    };

  },

  methods: {

    getLiveBlogs() {

      request.get('/read/' + id)

        .then(response => {

          this.blogs = response.data.data;

        });

    },

  },

  mounted() {

    this.getLiveBlogs();

  },

});


查看完整回答
反对 回复 2024-01-22
  • 1 回答
  • 0 关注
  • 28 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信