将 ES5 函数添加到使用 babel 编译的 vuejs 应用程序?

Adding ES5 functions to vuejs app compiled with babel?

问题

如何将我的变量添加到使用 babel 的 My VueJS app

背景

我有一个使用 Vue 和 Axios 的应用程序。它工作正常,但我添加了动态重新格式化字符串的功能,重新格式化字符串的代码在 my pen 中工作正常。

var brewer = document.getElementsByClassName('author-raw');
for (var contrib = 0; contrib < brewer.length; contrib++) {
  var matches = brewer[contrib].innerHTML.match(/(.*)\s\<([a-z]*)\>/);
  var output = `${matches[1]} <a href="https://www.twitter.com/${matches[2]}" target="_blank">@${matches[2]}</a>`;
  brewer[contrib].closest('div').querySelector('cite').innerHTML = output;
}

我现在需要将它添加到 my beer education app

我查看了 documentation for vue,我想我需要将它添加到创建的块中?它在那里不起作用。

created() {
  //code goes here?
}

在 React 中我可以,但这几乎在任何地方。


编辑 1

我忘了我应该转换成 ES6,所以更新的 JS 是

const brewer = document.getElementsByClassName('author-raw');
for (let contrib = 0; contrib < brewer.length; contrib++) {
  const matches = brewer[contrib].innerHTML.match(/(.*)\s\<([a-z]*)\>/);
  const output = `${matches[1]} <a href="https://www.twitter.com/${matches[2]}" target="_blank">@${matches[2]}</a>`;
  brewer[contrib].closest('div').querySelector('cite').innerHTML = output;
}

我不会尝试以这种方式操纵 DOM,而是操纵数据。

将您的 addBeer 方法更改为:

addBeer() {
  axios.get('https://api.punkapi.com/v2/beers/random')
    .then(response => {
      let api = response.data[0];

      // parse contributor here
      let contributor = api.contributed_by
      let matches = contributor.match(/(.*)\s\<([a-z]*)\>/)

      let apiInfo = {
        name: api.name,
        desc: api.description,
        img: api.image_url,
        tips: api.brewers_tips,

        // and add both parts to your data
        contributor: matches[1],
        twitter: `@${matches[2]}`,

        tagline: api.tagline,
        abv: api.abv,
        food: api.food_pairing
      };
      this.beers.push(apiInfo)
      if (this.bottomVisible()) {
        this.addBeer()
      }
  })
}

并更改模板以使用已解析的数据:

<span class="author-raw" aria-hidden="true">
  {{ beer.contributor }} 
  <a style="color: white" :href="`https://www.twitter.com/${beer.twitter}`">{{beer.twitter}}</a>
</span>

这是你的codepen updated

使用 Vue,如果您开始操作 DOM,除非您尝试与外部库集成,否则您几乎总是会做错。

另一种方法是编写一个小的功能组件。

const Contributor = {
  functional: true,
  render(h, context){
    const {contributor} = context.props
    // leave if there is no contributor
    if (!contributor) return null

    const parsed = contributor.match(/(.*)\s\<([A-Za-z]*)\>/)
    // leave if we couldn't parse the contributor
    if (!parsed || parsed.length < 2) return null

    const [original, name, handle] = parsed
    const twitter = `@${handle}`
    const href = `https://www.twitter.com/${twitter}`
    const props = {attrs: {href}, style:{color: "white", marginLeft: ".5em"}}
    return h("span", {attrs:{"aria-hidden": true}}, [name, h("a", props, [twitter])])
  }
}

并将您的模板更改为:

<div class="author">
  <contributor :contributor="beer.contributor"></contributor>
   <cite></cite>
</div>

这是你的 codepen updated 来证明这一点。