vuejs / vue

This is the repo for Vue 2. For Vue 3, go to https://github.com/vuejs/core
http://v2.vuejs.org
MIT License
207.87k stars 33.69k forks source link

Optional chaining in templates does not seem to work #11088

Closed DRoet closed 2 years ago

DRoet commented 4 years ago

Version

15.8.3

Reproduction link

https://template-explorer.vuejs.org/#%3Cdiv%20id%3D%22app%22%20v-if%3D%22obj%3F.a%22%3E%7B%7B%20msg%20%7D%7D%3C%2Fdiv%3E

Steps to reproduce

Use a v-if that uses optional chaining w/ @vue/cli version 4.2.0:

v-if="test?.length > 0"

What is expected?

no error is thrown

What is actually happening?

following error is thrown:

  Errors compiling template:

  invalid expression: Unexpected token '.' in

    test?.length > 0

  Raw expression: v-if="test?.length > 0"
haoqunjiang commented 4 years ago

As said in the release notes:

// Note: scripts only, support in template expressions only available in Vue 3

https://vue-next-template-explorer.netlify.com/#%7B%22src%22%3A%22%3Cdiv%20id%3D%5C%22app%5C%22%20v-if%3D%5C%22obj%3F.a%5C%22%3E%7B%7B%20msg%20%7D%7D%3C%2Fdiv%3E%22%2C%22options%22%3A%7B%22mode%22%3A%22module%22%2C%22prefixIdentifiers%22%3Afalse%2C%22hoistStatic%22%3Afalse%2C%22cacheHandlers%22%3Afalse%2C%22scopeId%22%3Anull%7D%7D

DRoet commented 4 years ago

ah derp, totally read over that comment

haoqunjiang commented 4 years ago

Technically, to support such syntaxes in Vue 2, we need to:

  1. tweak the codegen to not modify such expressions (currently it converts obj?.a to obj ? .a)
  2. vue-template-es2015-compiler needs to be able to parse such syntaxes (not necessarily to transpile, to parse is enough)
  3. backport this commit to vue-loader 15 https://github.com/vuejs/vue-loader/commit/4cb447426ec19c4e07f22ce73fe134f8abaf007c#diff-c735bef98c9338c75a676df1903d2afc
  4. get ready for the possible numerous bug reports

We don't have the capacity to implement it yet. But contributions are welcome.

jacekkarczmarczyk commented 4 years ago

https://github.com/vuejs/vue-next/commit/8449a9727c942b6049c9e577c7c15b43fdca2867#diff-1cb91d3fc9313f91590cd27606eade47R402

McPo commented 4 years ago

Potential workaround includes using lodash's get as stated in https://github.com/vuejs/vue/issues/4638#issuecomment-397770996

Another hack is to use eval.

As $eval was taken out in Vue 2, you'll have to create your own mixin so that it can be accessed in all components without having to import it into each one.

i.e.

Vue.mixin({
  methods: {
    $elvis: p => eval('this.'+p)
  }
});

Example template

<template>
<span>{{ $elvis('foo?.bar') }}</span>
</template>

Although its still no substitute for the real operator, especially if you have many occurrences of it

Edmund1645 commented 4 years ago

Although its still no substitute for the real operator, especially if you have many occurrences of it

@McPo Just how safe do you think this is? I'm about to use it in production code because I do not want to set computed properties for the numerous nested fields that may be undefined or null

McPo commented 4 years ago

Although its still no substitute for the real operator, especially if you have many occurrences of it

@McPo Just how safe do you think this is? I'm about to use it in production code because I do not want to set computed properties for the numerous nested fields that may be undefined or null

As far as Im aware, it should be fine, as youre in control of the input. The only issues would be if the developer wasnt aware that its using eval and allows user input to it, but that doesn't really make sense in the case of the elvis operator.

It may have a performance impact though, in that Vue will probably recall the method on every update. I would also suspect theres some overhead in calling eval in the first place. Providing its not in a tight loop, realistically you're not likely to notice a difference.

troxler commented 4 years ago

Please do not use eval for that. It generally is bad practice and in this case specifically, it breaks in all browsers that do not support optional chaining. Whether or not you are using Babel or any other transpiler is irrelevant as they cannot transpile strings.

A better way to access properties in a fail-safe way (like with optional chaining) is the following:

<template><div>
  {{getSafe(() => obj.foo.bar)}} <!-- returns 'baz' -->
  {{getSafe(() => obj.foo.doesNotExist)}} <!-- returns undefined -->
</div></template>

<script>
export default {
    data() {
        return {obj: {foo: {bar: 'baz'}}};
    },
    methods: {getSafe},
};
function getSafe(fn) {
    try { return fn(); }
    catch (e) {}
}
</script>

The getSafe function catches any exceptions and implicitly returns undefined if the property access fails. You could also create a mixin (or use the new composition API) to reuse that function.

McPo commented 4 years ago

Please do not use eval for that. It generally is bad practice and in this case specifically, it breaks in all browsers that do not support optional chaining. Whether or not you are using Babel or any other transpiler is irrelevant as they cannot transpile strings.

A better way to access properties in a fail-safe way (like with optional chaining) is the following:

<template><div>
  {{getSafe(() => obj.foo.bar)}} <!-- returns 'baz' -->
  {{getSafe(() => obj.foo.doesNotExist)}} <!-- returns undefined -->
</div></template>

<script>
export default {
    data() {
        return {obj: {foo: {bar: 'baz'}}};
    },
    methods: {getSafe},
};
function getSafe(fn) {
    try { return fn(); }
    catch (e) {}
}
</script>

The getSafe function catches any exceptions and implicitly returns undefined if the property access fails. You could also create a mixin (or use the new composition API) to reuse that function.

True I forgot to highlight the issue that it requires optional chaining to be supported in the browser. (Which isn't a major issue in my case, although I probably will stop using it anyway)

adjenks commented 4 years ago

For deeply nested complex objects, this seems really important. I have objects that are five layers deep. I like the getSafe() method described by troxler, but I would prefer that chaining just work. I mean... It wasn't "really important" to me before it became a feature in the language, but now that it's a feature, using getSafe() or other methods like that that I would use seems messy. So, I don't mean to nag, I'm just a user sharing my priorities. Thanks for all your hard work guys. Maybe I'll just try to prioritize the move to Vue 3.

tvkit commented 4 years ago

Using the following for a TS project:

  private s<T>(obj: T | undefined): T {
    return obj || ({} as T);
  }

with VUE expressions that look like:

<q-input 
  v-model="model.value"
  label="Eyeballs"
  type="number"
  :min="s(s(model).pirate).min"
  :max="s(model).max"
/>

Gets a bit nesty beyond the first property, but the linters are happy.

Juraj-Masiar commented 4 years ago

private s(obj: T | undefined): T { return obj || ({} as T); }

@tvkit that's not exactly good implementation as it won't work with any other falsy values like empty string, zero, false. So s('').length will give me undefined instead of zero.

Sceat commented 4 years ago

Using a function is outside the scope of this issue and not a viable replacement. However if someone need this kind of hack, use this :point_down:

const reducer = source => (object, property) => object?.[property] ?? undefined
const optional_chain = (...parameters) => {
    const [source, ...properties] = parameters
    return properties.reduce(reducer(source))
}
<div :foo="optional_chain({}, 'foo', 'bar', 'baz')" />
tvkit commented 4 years ago

@Juraj-Masiar Good point.

Baldrani commented 3 years ago

@Sceat I actually really like the idea.

edgarshurtado commented 3 years ago

I guess the idea is to use optional chaining in Single File Components. But, funny enough, if you import the template from an HTML or PUG file, it works. I'd guess it shouldn't work either.

MBearo commented 3 years ago

Using a function is outside the scope of this issue and not a viable replacement. However if someone need this kind of hack, use this 👇

const reducer = source => (object, property) => object?.[property] ?? undefined
const optional_chain = (...parameters) => {
  const [source, ...properties] = parameters
  return properties.reduce(reducer(source))
}
<div :foo="optional_chain({}, 'foo', 'bar', 'baz')" />

@Sceat It's not work.I fix it.

const optional_chain = (...parameters) => {
  const [source, ...properties] = parameters
  return properties.reduce((object, property) => object?.[property] ?? undefined, source)
}
const a={b:{c:{d:1}}}
console.log(optional_chain(a,'b','c','d'))
CMCDragonkai commented 3 years ago

I'm on Vue 3.0.0, and it still doesn't work. Did it work on a later version?

arielginsburg commented 3 years ago

I'm on Vue 3.0.0, and it still doesn't work. Did it work on a later version?

Same here. I thought this was getting fixed with the release of Vue 3. Guess not... 😔

jacekkarczmarczyk commented 3 years ago

Same here. I thought this was getting fixed with the release of Vue 3. Guess not... 😔

It does work in Vue 3

arielginsburg commented 3 years ago

Same here. I thought this was getting fixed with the release of Vue 3. Guess not... 😔

It does work in Vue 3

Not for me! I'm using vue 3.0.4 and vue-loader 16.1.2 and I get the following compiler error:

Module parse failed: Unexpected token (27:70)
File was processed with these loaders:
 * ./node_modules/vue-loader/dist/templateLoader.js
 * ./node_modules/vue-loader/dist/index.js
You may need an additional loader to handle the result of these loaders.
|         _createVNode("tr", null, [
|           _hoisted_4,
>           _createVNode("td", null, _toDisplayString(_ctx.currentTime ?? 'null'), 1 /* TEXT */)
|         ]),
|         _createVNode("tr", null, [

The breaking code in my template is the following:

<tr>
    <td>current time</td>
    <td>{{ currentTime ?? 'null' }}</td>
</tr>

Changing it to the following fixes the error:

<tr>
    <td>current time</td>
    <td>{{ currentTime || 'null' }}</td>
</tr>
LinusBorg commented 3 years ago

As you can see in the error message, the template was correctly converted, the render function code contains the optional chaining character as it should.

The error seems to come from webpack, as it states "File was processed with these loaders:"

maybe your babel setup doesn't contain support for transpiling optional chaining operators? hard to say without knowing the setup & config.

LinusBorg commented 3 years ago

Here's a codesandbox where it works fine: https://codesandbox.io/s/vigilant-bash-bjjvl?file=/src/App.vue

arielginsburg commented 3 years ago

Strange. My code compiles just fine using the nullish coalescing operator in Typescript. I only encounter the issue when using the operator in templates.

LinusBorg commented 3 years ago

Presumably because the Vue compiler generates JS and is never run through the TS compiler.

Anyways, thatbw9upe have to be discussed in the vue-next repo as that's about Vue 3

BoBoooooo commented 3 years ago

mark. Have the same problem with using ?. in template 2.x. Wait for support

douglasg14b commented 3 years ago

This would definitely be great to have in Vue2! Will there be support added?

baybal commented 3 years ago

Same behaviour for me on the latest Chrome, loader 16, and vue@latest

ghost commented 3 years ago

optional chaining support for Vue2 please! If I were to take a jab at this, is this still the right path?

andriusign commented 3 years ago

Optional chaining for Vue2 please!

JuniorTour commented 3 years ago

Try vue-template-babel-compiler

It will enable Optional Chaining(?.), Nullish Coalescing(??) and many new ES syntax for Vue.js SFC based on Babel.

Github Repo: vue-template-babel-compiler

DEMO

DEMO

Usage

Please refer to REAMDE for detail usage

Support for Vue-CLI, Nuxt.js, Webpack, vue-jest , any environment use vue-loader.

xianghongai commented 3 years ago

It is not correct to use the ?. syntax. The Vue design is to view the data binding on the data already processed by Reactive. It is a stable data model.

xianghongai commented 3 years ago

But from the perspective of JavaScript grammar, such support should be provided. What is executed is an expression and does not depend on the data model. 😂

ghost commented 3 years ago

But from the perspective of JavaScript grammar, such support should be provided. What is executed is an expression and does not depend on the data model. 😂

image

smitpatelx commented 3 years ago
/*
 * Where to use: Use in vue templates to determine deeply nested undefined/null values
 * How to use: Instead of writing parent?.child?.child2 you can write
 *            isAvailable(parent, 'child.child2')
 * @author    Smit Patel
 * @params    {Object} parent
 *            {String} child
 * @return    {Boolean}     True if all the nested properties exist
 */
export default function isAvailable(parent, child) {
  try {
    const childArray = String(child).split('.');
    let evaluted = parent;
    childArray.forEach((x) => {
      evaluted = evaluted[x];
    });
    return !!evaluted;
  } catch {
    return false;
  }
}

Use :

<template>
  <div>
    <span :v-if="isAvailable(data, 'user.group.name')">
      {{ data.user.group.name }}
    <span/>
  </div>
</template>
<script>
import isAvailable from 'file/path';
export default {
   methods: { isAvailable }
}
</script>
ankurk91 commented 3 years ago

https://github.com/developit/dlv

Shinigami92 commented 3 years ago

developit/dlv

This will neglect any typing and therefore not an acceptable option

mohamadrezahedayati commented 3 years ago

You can write a method that returns its value. example in under

template :

image

methods :

image

mohamadrezahedayati commented 3 years ago

@adjenks I know that when you write a function, the amount of code written increases but each increase not bad .

why :

  1. because your application logic is inside script not presentation layer
  2. because you can test it in the test unit.
  3. because according to the Clean Code Book , your application logic is inside a wrapper ( function ) , This helps to read the code and the others will understand the reason for this.
ghost commented 3 years ago

Checking property presence hardly constitutes as application logic. Having the function as a workaround is one thing, but stating that it is the preferred approach for the sake of clean code is a bit absurd.

joecampo commented 3 years ago

@mohamadrezahedayati Clean Code isn't just a book of hard and fast rules. By your logic, Vue components in themselves violate SRP.

@calevio is 100% correct.

tflori commented 3 years ago

In my opinion that is not logic by the mean of "no logic in views". v-if and v-for etc. are the type of logic that is meant by this sentence. And to create a method or calculated property is hiding what properties are used. It is therefore rather not clean code.. There is a reason behind the clean code policy and there are exceptions. If you couldn't write conditionals or loops in views you are back to static HTML. So it is common in every template language to write such logic in the view.

Shinigami92 commented 3 years ago

Please stop :stop_sign: the discussion about whether this feature is wanted or not. This is expected valid JS embedded in Vue templates and the JS/ECMA-version supported for embedded code in Vue template is just "outdated" and therefore doesn't support the optional chaining syntax.

I'm nut sure if we want to support it in Vue 2... I understand this. But in Vue 3 this is an essential need. (if not already possible, I'm sadly a bit behind due to lacking support of Vuetify)

Edit: Seems Vue 3 already supports it

cwilby commented 3 years ago

One more way to do this, didn't want to use lodash.

Add a mixin / function

Vue.mixin({
  methods: {
    $get(obj, path, defaultValue = null) {
      let result = obj;
      for (let piece of path.split('.')) {
        result = result[piece];
        if (!result || typeof result !== 'object') {
          return result || defaultValue;
        }
      }
      return defaultValue;
    }
  }
});

Use in templates

<template>
  <p>{{ $get(company, 'representative.address.street', '(No address)') }}</p>
</template>

May not (probably does not) work for all scenarios, but helped me move on.

Later I'll search replace with \$get\((.*?), '(.*?)'\).

maximilliangeorge commented 2 years ago

Try vue-template-babel-compiler

It will enable Optional Chaining(?.), Nullish Coalescing(??) and many new ES syntax for Vue.js SFC based on Babel.

Github Repo: vue-template-babel-compiler

DEMO

DEMO

Usage

Please refer to REAMDE for detail usage

Support for Vue-CLI, Nuxt.js, Webpack, vue-jest , any environment use vue-loader.

This works, thanks a lot! The only reply that didn't suggest various hacks and workarounds.

souljorje commented 2 years ago

Let's support this issue to implement it in vite & vue 2 https://github.com/underfin/vite-plugin-vue2/issues/161

caocos commented 2 years ago

In the file node_modules\vue-template-babel-compiler\lib\index.js

184 line find errors edit errors:[] good job

robert-niestroj commented 2 years ago

The blog post on Vue 2.7 https://blog.vuejs.org/posts/vue-2-7-naruto.html says:

2.7 also supports using ESNext syntax in template expressions.

Will this release solve this?

DRoet commented 2 years ago

@robert-niestroj I tested this today and it seems to work in v2.7 (make sure you have vue-loader >=v15.10 installed)

MartinX3 commented 2 years ago

Be aware that you can't use typescript there with Vue 2.7. If you need it use Vue 3.x.